The Fixed-Step Loop
Delta time keeps speeds constant, but a variable dt still makes physics depend on the frame rate: a jump can reach different heights on different machines, and replays drift apart. Most games therefore update the world in fixed steps (for example exactly 1/60 s each) and draw as often as the screen allows. The tool that connects the two is the accumulator.
The problem with a variable dt
A jump is gravity changing the velocity, and the velocity changing the position. The usual integration step is:
vy += gravity * dt; // velocity first
y += vy * dt; // then position (semi-implicit Euler)Run the same jump with different frame rates and the peak height changes:
function jumpPeak(dt) {
let y = 0, vy = -300, peak = 0; // jump up at 300 px/s (y grows downward)
const gravity = 900;
for (let t = 0; t < 1; t += dt) {
vy += gravity * dt;
y += vy * dt;
peak = Math.min(peak, y);
}
return -peak.toFixed(1);
}
console.log('144 fps:', jumpPeak(1 / 144));
console.log(' 60 fps:', jumpPeak(1 / 60));
console.log(' 30 fps:', jumpPeak(1 / 30));
console.log(' 10 fps:', jumpPeak(1 / 10));144 fps: 49
60 fps: 47.5
30 fps: 45
10 fps: 36
On a slow machine the player jumps lower, and in a platformer a ledge reachable at 144 FPS may be out of reach at 30 FPS. With a fixed step the simulation does exactly the same arithmetic on every machine, so the result is identical (the same holds for networked games and replays, which must stay in sync).
The accumulator
Each display frame adds the real elapsed time to an "accumulator" bucket. While the bucket holds at least one step, run one update and take one step out. Whatever is left over waits for the next frame:
const STEP = 1 / 60;
let acc = 0, last = performance.now();
function frame(now) {
acc += Math.min((now - last) / 1000, 0.25); // clamp: avoid the spiral of death
last = now;
while (acc >= STEP) {
update(STEP); // always the same dt
acc -= STEP;
}
draw(acc / STEP); // 0..1: how far we are between two updates
requestAnimationFrame(frame);
}Here is the bookkeeping on its own, fed with uneven frame times (in milliseconds) like a real browser produces:
function makeLoop(step) {
let acc = 0, updates = 0;
return function frame(ms) {
acc += ms / 1000;
let n = 0;
while (acc >= step - 1e-9) { acc -= step; n++; } // the epsilon absorbs float rounding
updates += n;
return `${String(ms).padStart(5)} ms -> ${n} update(s), left ${(acc * 1000).toFixed(2)} ms, total ${updates}`;
};
}
const frame = makeLoop(1 / 60);
for (const ms of [16.7, 16.6, 8.3, 8.4, 33.4, 6.9, 50]) console.log(frame(ms)); 16.7 ms -> 1 update(s), left 0.03 ms, total 1
16.6 ms -> 0 update(s), left 16.63 ms, total 1
8.3 ms -> 1 update(s), left 8.27 ms, total 2
8.4 ms -> 1 update(s), left 0.00 ms, total 3
33.4 ms -> 2 update(s), left 0.07 ms, total 5
6.9 ms -> 0 update(s), left 6.97 ms, total 5
50 ms -> 3 update(s), left 6.97 ms, total 8
Read it line by line: a 144 Hz display (6.9 ms frames) sometimes gets zero updates in a frame, a hitch (33 ms, 50 ms) gets two or three, and over time the game still runs exactly 60 updates per second.
The spiral of death
If one update takes longer than STEP to compute, every frame adds more time than it removes, the while loop runs more updates each frame, which makes frames even slower… and the game freezes. Two defences:
- Clamp the time added per frame (
Math.min(…, 0.25)): the game slows down instead of locking up. - Optionally cap the number of updates per frame (for example 5) and drop the rest of the accumulator.
Smooth drawing: interpolation
With 60 updates per second on a 144 Hz screen, some frames show the same positions twice and the motion looks slightly uneven. The fix is to draw objects between their previous and current positions, using alpha = acc / STEP:
// in update(): remember where things were
ball.prevX = ball.x;
ball.x += ball.vx * STEP;
// in draw(alpha):
const drawX = ball.prevX + (ball.x - ball.prevX) * alpha;The demo below exaggerates the effect: the physics runs at only 10 updates per second. Press I to toggle interpolation. Without it the ball jumps in visible steps; with it the motion is smooth, although the simulation is just as coarse. Press Space to make the ball jump.
<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 interpolate = true, jump = false;
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault();
if (e.code === 'KeyI') interpolate = !interpolate;
if (e.code === 'Space') jump = true;
});
const STEP = 1 / 10; // deliberately coarse: 10 updates per second
const ball = { x: 40, y: 220, prevX: 40, prevY: 220, vx: 120, vy: 0 };
let acc = 0, last = performance.now(), updates = 0;
function update(dt) {
ball.prevX = ball.x; ball.prevY = ball.y;
if (jump && ball.y >= 220) ball.vy = -420;
jump = false;
ball.vy += 900 * dt;
ball.x += ball.vx * dt;
ball.y += ball.vy * dt;
if (ball.y > 220) { ball.y = 220; ball.vy = 0; }
if (ball.x > 450 || ball.x < 30) ball.vx = -ball.vx;
updates++;
}
function draw(alpha) {
const a = interpolate ? alpha : 1;
const x = ball.prevX + (ball.x - ball.prevX) * a;
const y = ball.prevY + (ball.y - ball.prevY) * a;
ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, 480, 270);
ctx.fillStyle = '#455a64'; ctx.fillRect(0, 235, 480, 35);
ctx.fillStyle = '#ffca28';
ctx.beginPath(); ctx.arc(Math.round(x), Math.round(y), 15, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#fff'; ctx.font = '14px system-ui, sans-serif'; ctx.textAlign = 'left';
ctx.fillText(`Interpolation: ${interpolate ? 'ON' : 'OFF'} (I) Space: jump updates: ${updates}`, 10, 22);
ctx.fillText(`alpha = ${alpha.toFixed(2)}`, 10, 42);
}
requestAnimationFrame(function frame(now) {
acc += Math.min((now - last) / 1000, 0.25);
last = now;
while (acc >= STEP) { update(STEP); acc -= STEP; }
draw(acc / STEP);
requestAnimationFrame(frame);
});
</script>Tip: Real games use 60 (sometimes 120) updates per second, where the steps are small enough that many 2D games skip interpolation entirely. The play kit used in this course does exactly that:
update(1/60)in a fixed-step loop,draw()once per frame, no interpolation.
Which loop should I use?
| Loop | Good for |
|---|---|
Variable dt (update and draw once per frame) |
Simple animations, menus, games without precise physics |
| Fixed step + draw every frame | Platformers, physics, anything that must behave identically everywhere |
| Fixed step + interpolation | Low update rates, or high-refresh screens where smoothness matters a lot |
Test yourself
With STEP = 1/60, a frame takes 40 ms and the accumulator held 5 ms before it. How many updates run in this frame?
- 1
- 2
- 3
- 40
Why does a fixed step make a jump reach the same height on every machine?
- Because it runs faster
- Because every machine performs exactly the same updates with the same dt
- Because it uses integers
- Because the browser caps the frame rate
What does alpha = acc / STEP tell the draw function?
- The frame rate
- How far the current moment is between the previous and the next update (0 to 1)
- The transparency of sprites
- The number of updates left