TExcelTAD
Home › 2D Games with JavaScript & Canvas › requestAnimationFrame & Delta Time

requestAnimationFrame & Delta Time

A game is a loop: read input, update the world a little, draw it, repeat, many times per second. In the browser that loop is driven by requestAnimationFrame. This lesson shows how it works, and why every movement must be multiplied by delta time, the time since the last frame.

The loop

requestAnimationFrame(callback) asks the browser to call callback once, just before it paints the next frame. To get a loop, the callback requests the next frame itself:

js
function frame(now) {           // now = timestamp in milliseconds
  update();
  draw();
  requestAnimationFrame(frame); // schedule the next frame
}
requestAnimationFrame(frame);

Why not setInterval(frame, 16)?

requestAnimationFrame setInterval / setTimeout
Timing Synced to the screen refresh (60, 120, 144 Hz…) Fires whenever the timer is due, out of step with the display, so motion stutters
Hidden tab Paused, saving battery Keeps running (throttled to about once per second)
Timestamp Passed to the callback, the same for every callback in this frame You call performance.now() yourself

The trap: moving "per frame"

The simplest movement is x += 2 every frame. That means 2 pixels per frame, so the speed depends on the screen: 120 pixels per second on a 60 Hz monitor, 288 on a 144 Hz gaming monitor, and slower whenever the game drops frames. This little simulation moves an object for one second at different frame rates:

js · try it yourself
function simulate(fps, perFrame) {
  const dt = 1 / fps;
  let xFrame = 0, xTime = 0;
  for (let i = 0; i < fps; i++) {        // one second of frames
    xFrame += perFrame;                  // "2 pixels per frame"
    xTime += 120 * dt;                   // "120 pixels per second" x seconds
  }
  return { fps, perFrame: xFrame, withDeltaTime: Math.round(xTime) };
}
for (const fps of [30, 60, 144]) console.log(simulate(fps, 2));
{ fps: 30, perFrame: 60, withDeltaTime: 120 }
{ fps: 60, perFrame: 120, withDeltaTime: 120 }
{ fps: 144, perFrame: 288, withDeltaTime: 120 }

With delta time (dt, the seconds since the last frame), you write speeds in units per second and multiply: x += speed * dt. The distance per second is then the same at any frame rate.

Delta time in practice

js
let last = performance.now();
function frame(now) {
  let dt = (now - last) / 1000;   // milliseconds -> seconds
  last = now;
  dt = Math.min(dt, 0.1);         // clamp: see below
  update(dt);
  draw();
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

The clamp protects against huge steps. If the tab was hidden for 10 seconds, or the debugger paused the page, the next dt would be 10, and a ball moving at 300 px/s would jump 3000 pixels, straight through walls. Capping dt at 0.1 s makes the game slow down briefly instead.

See the difference

The demo moves two squares at "the same speed". The top one moves 2 px per frame, the bottom one 120 px/s × dt. Press 1, 2 or 3 to simulate a 60, 30 or 15 FPS machine (the demo skips frames). The top square slows down on a slow machine; the bottom one keeps its speed and just moves in bigger steps.

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
let skip = 1;                         // run logic on every Nth browser frame
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault();
  if (e.code === 'Digit1') skip = 1;
  if (e.code === 'Digit2') skip = 2;
  if (e.code === 'Digit3') skip = 4;
});

const perFrame = { x: 0 }, perSecond = { x: 0 };
let last = performance.now(), count = 0, fps = 0, fpsFrames = 0, fpsTime = 0;

function frame(now) {
  requestAnimationFrame(frame);
  if (++count % skip !== 0) return;   // pretend this machine is slower
  const dt = Math.min((now - last) / 1000, 0.1);
  last = now;
  fpsFrames++; fpsTime += dt;
  if (fpsTime >= 0.5) { fps = Math.round(fpsFrames / fpsTime); fpsFrames = 0; fpsTime = 0; }

  perFrame.x = (perFrame.x + 2) % 480;              // per frame: speed depends on FPS
  perSecond.x = (perSecond.x + 120 * dt) % 480;     // per second: speed is constant

  ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, 480, 270);
  ctx.fillStyle = '#ef5350'; ctx.fillRect(Math.round(perFrame.x), 70, 30, 30);
  ctx.fillStyle = '#66bb6a'; ctx.fillRect(Math.round(perSecond.x), 170, 30, 30);
  ctx.fillStyle = '#fff'; ctx.font = '14px system-ui, sans-serif'; ctx.textAlign = 'left';
  ctx.fillText('x += 2 (per frame)', 10, 60);
  ctx.fillText('x += 120 * dt (per second)', 10, 160);
  ctx.fillText(`~${fps} FPS   (click, then press 1 / 2 / 3)`, 10, 20);
}
requestAnimationFrame(frame);
</script>

Note: Delta time fixes the speed, not everything. With a variable dt, physics such as jumping can still land at slightly different heights on different machines, and fast objects can skip through thin walls when a frame takes long. The next lesson fixes that with a fixed-step loop.

Stopping the loop

requestAnimationFrame returns an id. Keep it if you need to stop the loop, for example when a level ends or the game is removed from the page:

js
let rafId = requestAnimationFrame(frame);   // inside frame(): rafId = requestAnimationFrame(frame);
cancelAnimationFrame(rafId);

Test yourself

A ball moves with x += 3 every frame. How far does it move in one second on a 120 Hz screen?

  1. 3 pixels
  2. 180 pixels
  3. 360 pixels
  4. It is the same on every screen

With delta time, what does x += 200 * dt mean?

  1. 200 pixels per frame
  2. 200 pixels per second, whatever the frame rate
  3. 200 milliseconds per pixel
  4. Move 200 pixels once

Why clamp dt (for example to 0.1 s)?

  1. To limit the game to 10 FPS
  2. So a long pause (hidden tab, debugger) doesn't produce one giant step that skips through walls
  3. Because requestAnimationFrame can return negative times
  4. To save battery