Adding the Game Loop

As you already know, the actual execution of your game from frame to frame is orchestrated by the game loop, which is responsible for updating the game state and then rendering the current frame of the game on the screen. The main rendering and JavaScript engine in your browser both run together in a single thread, which means that you can’t use a single tight loop for the game loop as you might in an environment with true multithreading. Instead, as you saw in the first chapter, your game loop must be run with a timer that cedes control from your JavaScript code back to the browser, so it can update the page and handle input events.

Building a Better Game Loop Timer

For a long time building a game loop timer was done with the timer functions that have always existed in the browser: setTimeout and setInterval. Although this worked acceptably to a certain degree, it suffered from a few drawbacks.

The first drawback was that, especially on slower computers and browsers, the game might try to update the game more often than the browser could handle, resulting in a visual slow-down. The second drawback was that even when the browser had a different tab active, the game would continue running at full speed, slowing down the computer and giving JavaScript games a bad name.

Starting in 2011, browsers began adding support for the requestAnimationFrame API, which allowed the browser to control the rate at which the game loop was called based on how fast the browser ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.