The Game Loop

Every game has a heartbeat. It's an infinite loop that runs 60 times every second, updating the world and drawing it to the screen.

Why do we need a loop?

Unlike a static website, a game is a dynamic simulation. Characters move, physics calculations happen, and inputs are processed constantly. To achieve this, we need a function that runs repeatedly.

In modern HTML5 development, the specialized function for this is requestAnimationFrame.

The Anatomy of a Frame

Each iteration of the loop (a "frame") typically performs three steps:

  1. Update: Calculate new positions, check collisions, process input.
  2. Clear: Wipe the canvas clean from the previous frame.
  3. Draw: Render everything in their new positions.

See it in action

We've prepared a live demo of a basic game loop. You can modify the speed and color instantly.

Open in Playground

The Code

Here is the minimal template for any HTML5 Canvas game:

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

let x = 0;

function gameLoop() {
    // 1. UPDATE state
    x += 2; // Move logic
    if (x > canvas.width) x = 0;

    // 2. CLEAR canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 3. DRAW everything
    ctx.fillStyle = '#4ade80';
    ctx.fillRect(x, 100, 50, 50);

    // 4. REPEAT
    requestAnimationFrame(gameLoop);
}

// Start the engine!
gameLoop();

Why not setInterval?

You might be tempted to use setInterval(loop, 16). Don't do it! requestAnimationFrame is superior because: