Game Timer Loop

Games on HTML5 Canvas require the use of the repeated update/render loop to simulate animation. We do this by using the setTimeout() JavaScript function, which will repeatedly call a function of our choosing at millisecond intervals. Each second of game/animation time is made up of 1,000 milliseconds. If we want our game to run at 30 update/render cycles per second, we call this a 30 frames per second (FPS) rate. To run our interval at 30 FPS, we first need to divide 1,000 by 30. The result is the number of milliseconds in each interval:

const FRAME_RATE = 30;
var intervalTime = 1000/FRAME_RATE;

gameLoop()

function gameLoop() {
         drawScreen();
         window.setTimeout(gameLoop, intervalTime);
    }

By calling the drawScreen() function repeatedly on each interval time-out, we can simulate animation.

Note

Sometimes we will refer to each of the frame intervals as a frame tick.

Get HTML5 Canvas, 2nd Edition 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.