Game Loop

In this lesson, you will learn how to make the central function of the game: the game loop.

We'll cover the following

Most games have one main function that keeps the game running even when the user isn’t doing anything. This cycle of running the same core function over and over again is called the game loop.

In our game, we need the loop to move the tetrominoes down the screen. We drop the tetromino down one row for every time frame.

RequestAnimationFrame

To create our game loop, we use requestAnimationFrame. It tells the browser that we want to animate, and it should call a function to update an animation before the next repaint. In other words, we tell the browser: “Next time you paint on the screen, also run this function because I want to paint something too.”

“Animation is not the art of drawings that move but the art of movements that are drawn.” — Norman McLaren

The way to animate with requestAnimationFrame() is to create a function that paints a frame and then re-schedules itself:

function animate() {  
  piece.draw();  
  requestId = requestAnimationFrame(animate);  
}

The requestAnimationFrame method returns an ID that we can use for canceling the scheduled animation frame with the cancelAnimationFrame method.

cancelAnimationFrame(id);

We can remove all our previous calls to draw() and instead call animate() from the play() function to start the animation. If we play the game, it should still run like before.

Why should we use requestAnimationFrame instead of setInterval or setTimeout?

  • It enables browser optimizations.
  • It handles the frame rate.
  • Animations only run when visible.

Timer

Next, we need a timer that keeps track of when we should move the tetromino down a line. Instead of creating the timeStart, timeElapsed and timeLevel variables, we can conveniently keep them together in an object literal:

let time = { start: 0, elapsed: 0, level: 1000 };

In the game loop, we update the game state based on the time interval, depending on which level the player is on, and then we draw the result:

Get hands-on with 1400+ tech skills courses.