HTML5 game publishing

A Fixed Timestep Game Loop for Browser Games: Same Speed on Every Screen

Why games run faster on 144 Hz screens, the accumulator loop, clamping, interpolation, input and timers.

PlayKovo Team5 min read
Games currently available on PlayKovo. Open a title to see its current listing.

A game that runs perfectly on your 60 Hz monitor can feel wrong on a 144 Hz gaming laptop: jumps go higher, enemies move faster, physics behaves differently. Or it runs fine until the tab is backgrounded, and when the player returns, everything has fallen through the floor. These bugs come from the game loop. This post explains the fixed timestep loop, why it fixes them, and how to implement it in a browser game.

The naive loop

function frame() {
  player.x += player.speed;   // move a fixed amount per frame
  render();
  requestAnimationFrame(frame);
}

requestAnimationFrame runs at the display's refresh rate. On a 60 Hz screen, the player moves 60 times per second. On a 144 Hz screen, 144 times. The game literally runs more than twice as fast. Many first browser games ship with this bug.

Variable timestep: better, but not enough

let last = performance.now();
function frame(now) {
  const dt = (now - last) / 1000;
  last = now;
  player.x += player.speed * dt;   // speed in units per second
  render();
  requestAnimationFrame(frame);
}

Multiplying by elapsed time fixes the speed problem for simple movement. But it creates others:

  • Physics is not consistent. Integrating gravity and velocity with different step sizes gives slightly different results. A jump that clears a gap at 60 fps may fall short at 30 fps.
  • Large steps break collisions. If a frame takes 200 ms (a hitch, or a background tab returning), a fast object moves far enough in one step to pass through a wall.
  • Replays and determinism are impossible. The same inputs do not give the same result on different machines.

Fixed timestep with an accumulator

The standard solution, described in Glenn Fiedler's well-known article "Fix Your Timestep!", separates simulation from rendering. The simulation always advances in equal steps, for example 1/60 of a second. Rendering happens whenever the browser allows.

const STEP = 1 / 60;
const MAX_FRAME = 0.25;     // never simulate more than 250 ms at once
let acc = 0;
let last = performance.now();

function frame(now) {
  let dt = (now - last) / 1000;
  last = now;
  if (dt > MAX_FRAME) dt = MAX_FRAME;
  acc += dt;

  while (acc >= STEP) {
    update(STEP);           // always the same step size
    acc -= STEP;
  }

  const alpha = acc / STEP; // how far we are into the next step
  render(alpha);
  requestAnimationFrame(frame);
}

How it works:

  • Real elapsed time goes into an accumulator.
  • As long as there is at least one full step of time, the game runs update(STEP).
  • On a 144 Hz screen, many frames run zero updates and just render. On a 30 fps phone, each frame runs two updates.
  • Either way, the simulation advances 60 times per second of real time, with identical steps.

The spiral of death and the clamp

If update is slow, and the device cannot run 60 updates per second, the accumulator keeps growing, each frame runs more updates, which takes even longer. The game freezes. The MAX_FRAME clamp prevents that: at worst, the game slows down instead of locking up.

The clamp also handles background tabs. Browsers pause or heavily throttle requestAnimationFrame in hidden tabs. When the player returns, the first dt may be minutes long. Without the clamp, the game would try to simulate minutes in one frame. With it, at most 250 ms. Better still, pause the game when the page is hidden, using visibilitychange.

Interpolation: smooth rendering

With a fixed step of 60 Hz on a 144 Hz screen, objects only move on some frames, which looks slightly jerky. Interpolation fixes it. Keep the previous and current position of each object, and render between them using alpha:

function update(step) {
  for (const e of entities) {
    e.prevX = e.x; e.prevY = e.y;
    e.x += e.vx * step;
    e.y += e.vy * step;
  }
}

function render(alpha) {
  for (const e of entities) {
    const x = e.prevX + (e.x - e.prevX) * alpha;
    const y = e.prevY + (e.y - e.prevY) * alpha;
    draw(e, x, y);
  }
}

The rendered position is up to one step behind the simulation, which is about 16 ms at 60 Hz. Players do not notice that delay, but they do notice the smoothness. For teleports, such as a respawn, set prev equal to the new position so the object does not appear to slide across the screen.

Choosing a step size

  • 60 Hz is a good default for most games.
  • 30 Hz can be enough for slow puzzle or strategy games, and halves CPU use for simulation. Interpolation keeps rendering smooth.
  • 120 Hz or more helps for fast physics with small objects, but costs CPU. Physics engines often run substeps internally for that reason.

Engines and libraries usually have this built in. Phaser, for example, offers options for a fixed physics step, and physics libraries such as cannon-es and Rapier step at a fixed rate when you call them in an accumulator loop. Check what your engine does before writing your own.

Input with a fixed step

Input arrives as events between frames. Collect it, and let update read it. One catch: if a frame runs two updates, a "just pressed" flag might trigger twice, or if it runs zero, it might be lost. Clear "pressed this frame" flags after the first update that reads them, not at the end of the render frame.

Timers and cooldowns

Once you have a fixed step, use simulation time for everything gameplay-related: cooldowns, spawn timers, power-up durations. Count steps or add up STEP. Never use Date.now() or setTimeout for gameplay timing. They keep running while the game is paused and are not tied to the simulation.

Debugging tips

  • Test with Chrome DevTools' CPU throttling (4x or 6x slowdown) to simulate a weak phone.
  • If you can, test on a high refresh rate screen. Or temporarily call render twice per frame and skip requestAnimationFrame pacing to simulate it.
  • Switch tabs for a minute, come back. Nothing should jump.
  • Show a small debug counter of updates per second and frames per second. Updates should stay at your step rate.

Checklist

  • Simulation runs in fixed steps from an accumulator.
  • Frame delta is clamped.
  • Game pauses on visibilitychange.
  • Rendering interpolates between previous and current state.
  • Gameplay timers use simulation time.
  • Tested on low frame rates and high refresh rates.

More practical guides for HTML5 developers are on the PlayKovo developer blog.

We use optional cookies for site analytics and site advertising. You can change your choice later. Privacy policy.