DEV Community

Cover image for Metronome Physics: Fixed Timestep Game Loops and Render Interpolation in TypeScript
mustafa morbel
mustafa morbel

Posted on Originally published at javascript.plainenglish.io

Metronome Physics: Fixed Timestep Game Loops and Render Interpolation in TypeScript

Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link.

🎮 Try the Live Interactive Demo · 📦 GitHub Repo & Vitest Suite · ⚡ Get the TS 2D Canvas Physics Starter Kit

Interactive Demo Preview

Architecture diagram of a TypeScript fixed-timestep 60Hz physics metronome decoupled from 144Hz Canvas render interpolation
A 60Hz fixed-timestep accumulator drives deterministic physics while alpha interpolation keeps 144Hz rendering smooth.

Quick Takeaways

  • Accumulator Loop: Advance physics in invariant STEP = 1 / 60 slices so trajectories match bit-for-bit at any FPS.
  • Spiral-of-Death Guard: Clamp spikes (MAX_FRAME) and cap sub-steps (MAX_STEPS) so slow frames never freeze the tab.
  • Alpha Render Interpolation: Blend lerp(prev, pos, alpha) using remainder acc / STEP for silky 144Hz visuals.

Last week, I launched the exact same game on two different computers. My desktop has a 144 Hz gaming monitor; my aging laptop struggles to hit 40 FPS on a good day. I launched the ball from the exact same coordinates at the exact same angle.

On the two machines, the ball landed in two completely different places.

In game development, this is a nightmare.

A physics simulation should never depend on the screen's refresh rate. Whether a player sees 60 FPS, 30 FPS, or 144 FPS must not dictate where a projectile lands. Yet that was precisely what our physics engine was doing. At the core of that custom-built engine from our previous article, the heartbeat was this loop:

// Reminder from canvas-physics-from-scratch — OLD, variable-dt loop.
// Counter-example only; not in this project's repo.
const dt = Math.min((now - last) / 1000, 1 / 30); // delta time between frames
last = now;

world.step(dt); // advance physics by elapsed time
draw();
Enter fullscreen mode Exit fullscreen mode

In that project, we capped dt (delta time, the elapsed seconds between frames) with Math.min so that switching browser tabs wouldn't cause the ball to teleport through walls upon return. It was a small band-aid. In this article, we peel off that band-aid and heal the underlying wound: we make physics fixed-timestep and completely decouple rendering from it. By the end, we'll have a loop that behaves identically down to the bit on every single machine, yet still paints effortlessly at 144 frames per second.

The mental model for this entire piece is a metronome — because the whole design revolves around a single core idea. A variable-dt physics loop behaves like an emotional drummer: when excited (a fast machine), they speed up; when exhausted (a sluggish machine), they drag behind. The same song sounds completely different every time. We are going to put a metronome in front of this drummer. The metronome clicks exactly 60 times every second — regardless of the hardware. The renderer, meanwhile, behaves like an independent dancer flowing at their own tempo. The entire craft lies in separating the two, and then connecting them with mathematical elegance.

Our roadmap covers five key steps: dissecting the nonlinear math of variable delta time, building an accumulator loop, neutralizing the catastrophic "spiral of death," synthesizing in-between frames with render interpolation, and proving bit-for-bit determinism with automated Vitest suites.


Comparison diagram showing projectile trajectory divergence under variable delta-time semi-implicit Euler integration
Variable delta time causes semi-implicit Euler trajectories to drift across different display refresh rates.

The Variable-dt Trap

First, let's look closely at the problem. "It plays differently on every machine" might sound like a vague observation, but beneath it lies hard, unforgiving mathematics.

Our physics engine uses semi-implicit Euler (symplectic Euler) integration. It takes just two lines:

b.vel = add(b.vel, scale(this.gravity, dt)); // velocity += gravity * dt
b.pos = add(b.pos, scale(b.vel, dt));        // position += (new) velocity * dt
Enter fullscreen mode Exit fullscreen mode

The subtle trap lives in the second line: the position update uses the newly computed velocity for that frame. This gives the integrator its beloved numerical stability — but it also makes position updates nonlinear with respect to dt. If you take a time interval dt and split it into two sub-steps of dt / 2, you get a different mathematical result than taking a single step of dt.

Let's do the algebra by hand.

Taking a single step of duration dt:

v₁ = v₀ + g · dt
x₁ = x₀ + v₁ · dt = x₀ + v₀ · dt + g · dt²
Enter fullscreen mode Exit fullscreen mode

Now let's divide the exact same elapsed time into two steps of dt / 2.

First half-step:

v½ = v₀ + g · (dt / 2)
x½ = x₀ + v½ · (dt / 2) = x₀ + v₀ · (dt / 2) + g · (dt² / 4)
Enter fullscreen mode Exit fullscreen mode

Second half-step:

v₁ = v½ + g · (dt / 2) = v₀ + g · dt
x₂ = x½ + v₁ · (dt / 2) = x₀ + v₀ · dt + (3/4) · g · dt²
Enter fullscreen mode Exit fullscreen mode

Compare the position results: g · dt² versus (3/4) · g · dt².

The exact same physical duration yields two different spatial positions. Purely because we chopped up time differently.

That is why my 144 Hz monitor and my 40 FPS laptop diverged. The fast machine took many tiny dt steps; the slow machine took fewer, larger dt steps. Even with the same total elapsed time, the trajectories drifted apart.

To make matters worse, think about what Math.min(dt, 1 / 30) does on a slow machine: if a frame takes 40 ms, we tell physics that only 33.3 ms passed. 6.7 milliseconds simply evaporate into thin air. The physics simulation literally falls behind real time.

And then there is tunneling. When dt grows large, position += velocity * dt causes objects to leap across vast distances in a single frame. A fast-moving projectile can jump clean from one side of a thin barrier to the other without ever touching it — completely bypassing collision detection. On low-FPS hardware, tunneling is rampant. Our old band-aid (Math.min) existed solely to keep those jumps small. It didn't solve the problem; it merely swept it under the rug.

So, how do we build the metronome?


Timeline diagram converting irregular browser frame intervals into uniform 16.67ms fixed-timestep accumulator physics ticks
The accumulator stores irregular wall-clock frame durations and spends them in uniform 16.67ms (60Hz) physics steps.

Setting the Metronome: The Fixed-Timestep Accumulator

The concept is surprisingly simple. We will never tell the physics engine: "advance by however much real time just elapsed." Instead, we advance it by an invariant, fixed slice of time: STEP = 1 / 60 seconds. That is the metronome's tick interval.

Real Time (irregular): |-- 16ms --|--- 22ms ---|- 14ms -|
Metronome (fixed):     |- 16.6ms -|- 16.6ms -|- 16.6ms -|
Enter fullscreen mode Exit fullscreen mode

But real-world wall-clock time is anything but fixed. One frame takes 16.6 ms, another 22 ms, then the user switches tabs and 400 ms elapses. How do we convert this irregular real time into deterministic, uniform ticks?

With a piggy bank. In game architecture, this pattern is called an accumulator.

On every frame, we deposit the elapsed real time into the accumulator. If at least one full STEP has accumulated, we spend one tick. If two STEPs have accumulated, we spend two ticks. If there is less than STEP remaining in the accumulator, we don't spend it — we carry that fractional remainder over to the next frame.

// Step 1: Naive accumulator — no spiral-of-death protection, no snapshots yet.
// Pedagogical stepping stone: final implementation is in src/sim.ts + src/demo.ts.
const STEP = 1 / 60; // Metronome tick interval — physics advances 60 times a second
let acc = 0;         // Accumulator: unspent wall-clock time
let last = performance.now();

function frame(now: number) {
  const frameTime = (now - last) / 1000; // seconds elapsed this frame
  last = now;

  acc += frameTime; // deposit real time into the accumulator

  while (acc >= STEP) {
    world.step(STEP); // every tick consumes the EXACT same slice of time
    acc -= STEP;
  }

  draw();
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
Enter fullscreen mode Exit fullscreen mode

Notice the critical difference: world.step no longer receives frameTime. It always receives STEP. Physics cares how many times it gets called, but every invocation executes with the identical time step. A fast machine might run one tick per frame, while a struggling machine runs three — but every individual tick executes the exact same step(STEP) equation. A 10-second simulation runs exactly 600 ticks on both machines. Same sequence, same time step, identical outcome.

The dt / 2 divergence from the previous section completely vanishes: there is no dt / 2 anymore. There is only STEP, always STEP.

requestAnimationFrame simply hooks into the display refresh cycle: the browser calls frame right before painting, passing high-resolution timestamp now. The browser counts real time for us; our sole job is to slice it into uniform chunks.


Flowchart illustrating the game loop spiral of death and how MAX_FRAME clamping plus a MAX_STEPS ceiling prevent freezes
Clamping frame spikes with MAX_FRAME and capping sub-steps with MAX_STEPS prevents runaway CPU catch-up loops.

The Spiral of Death and Breaking the Loop

Take a hard look at the while loop above. There is a hidden landmine inside it.

What happens if a frame takes an unusually long time? Suppose the user minimizes the tab, the laptop goes to sleep, or the garbage collector pauses execution. Suddenly, frameTime arrives at 3.0 seconds.

We deposit 3 seconds into the accumulator. To empty it, the while loop must execute 180 physics ticks in a single frame. But running 180 physics steps takes time — say, 50 ms. While those 50 ms are running, more wall-clock time elapses, filling the accumulator further before the frame can even finish. The loop can never catch up. The browser hangs, the CPU pegs at 100%, and the laptop fans spin up like a jet engine.

In game engineering, this is known as the spiral of death: the metronome demands more ticks than your CPU can afford to pay. As you scramble to catch up, the debt grows; as the debt grows, catching up becomes even more impossible. A classic infinite downward spiral.

The solution has two layers:

  1. Clamp catastrophic frame spikes at the source. This is the legitimate, rightful place for our Math.min reflex.
  2. Impose a tick ceiling per frame. If we hit the ceiling, we make an executive decision: we forgive the unpayable debt.
// Step 2: Frame clamping + tick ceiling added (snapshots still to come).
// Full implementation in src/demo.ts (STEP is a `let` there to support runtime slider changes).
const STEP = 1 / 60;
const MAX_STEPS = 5;    // At most 5 physics ticks per frame
const MAX_FRAME = 0.25; // Clamp any single frame to 250ms

let acc = 0;
let last = performance.now();

function frame(now: number) {
  let frameTime = (now - last) / 1000;
  last = now;

  if (frameTime > MAX_FRAME) frameTime = MAX_FRAME; // 1) Clamp giant spikes
  acc += frameTime;

  let steps = 0;
  while (acc >= STEP && steps < MAX_STEPS) {         // 2) Impose tick ceiling
    world.step(STEP);
    acc -= STEP;
    steps++;
  }

  if (steps === MAX_STEPS) acc = 0; // 3) Hit the ceiling: drop debt to break the death spiral

  draw();
  requestAnimationFrame(frame);
}
Enter fullscreen mode Exit fullscreen mode

The line if (steps === MAX_STEPS) acc = 0; is deliberate surrender. It says: "This machine cannot keep up with real time right now. Instead of burning down the CPU trying to catch up, let's discard the lost time."

The result? On extreme frame drops or heavy tab switches, the game temporarily slows down (slow motion) instead of freezing solid. Among bad options, it is by far the best engineering compromise.

Tuning these numbers depends on your game's workload. MAX_STEPS = 5 at 60 Hz provides an 83 ms catch-up budget per frame — plenty for most web games. For heavy simulations, you might tune it to 3; for lightweight loops, 10. There is no magic number; you profile and decide.


Diagram showing temporal aliasing jitter when 144Hz display rendering reads uninterpolated 60Hz discrete physics positions
Drawing discrete 60Hz physics ticks directly on a 144Hz monitor produces draw-draw-jump temporal aliasing.

Decoupling Update from Render

So far, our metronome ticks reliably. But run this code on screen, and an ugly visual problem immediately jumps out at you.

Physics updates 60 times a second. If you have a 144 Hz display, you are drawing 144 frames per second — but physics isn't updating that frequently. On many frames, the while loop doesn't tick at all (the accumulator hasn't gathered a full STEP yet).

On that frame, you draw the ball at the exact same position as the previous frame. Then on the next frame, it's still in the same place. Then suddenly a tick executes, and the ball jumps. Draw-draw-jump, draw-draw-jump.

This visual artifact is called temporal aliasing, and your eyes register it as irritating micro-stutter (visual jitter). Here is the cruel irony: our physics is now completely deterministic and mathematically correct, yet the animation looks noticeably choppier. Because rendering is trapped by the discrete ticks of the physics engine.

The breakthrough insight: Update runs at a fixed rate; Render runs at the display's refresh rate — and Render interpolates the gap between physics ticks.

Physics marches to the metronome; the renderer dances at screen refresh rate. Our job is to synthesize the dancer's in-between poses.

To do that, all we need is the leftover remainder in the accumulator. When the while loop finishes, acc contains a fraction of time strictly less than STEP — representing how close we are to the next tick. We normalize this into a 0 to 1 progress ratio:

const alpha = acc / STEP; // Between 0 and 1: progress between the last tick and the next tick
Enter fullscreen mode Exit fullscreen mode

alpha = 0 means "we are sitting exactly on the last tick." alpha = 0.5 means "we are halfway between two ticks." This single scalar is the key to silky-smooth rendering.


Vector diagram of linear render interpolation blending previous and current physics snapshots using alpha remainder ratio
Linear interpolation blends prev and pos by alpha = acc / STEP, trading one tick of latency for liquid-smooth motion.

Render Interpolation: Drawing Between the Ticks

Now that we have alpha, we need one more ingredient: each body must retain both its current position (pos) and its position at the previous tick (prev). By interpolating between prev and pos by factor alpha, we draw the body exactly where it should appear at that sub-frame instant.

Previous (prev) ---- Render (alpha) ---- Current (pos)
  [ t = 0.0 ]         [ t = 0.65 ]        [ t = 1.0 ]
Enter fullscreen mode Exit fullscreen mode

This requires a tiny addition to our physics engine: right before every tick, copy the current position into prev.

// src/world.ts — also includes a createBody helper (where prev initializes to pos)
export interface Body {
  pos: Vec2; // current (curr) position
  prev: Vec2; // position at previous tick — used for interpolation
  vel: Vec2;
  radius: number;
  bounciness: number;
}

export class World {
  bodies: Body[] = [];
  gravity: Vec2;

  constructor(public width: number, public height: number, gravityY = 900) {
    this.gravity = vec(0, gravityY);
  }

  add(b: Body): Body {
    this.bodies.push(b);
    return b;
  }

  // Called BEFORE stepping: prev = curr. The "past" endpoint of interpolation.
  snapshot() {
    for (const b of this.bodies) {
      b.prev.x = b.pos.x;
      b.prev.y = b.pos.y;
    }
  }

  // Single FIXED step — dt is identical (STEP) on every call.
  step(dt: number) {
    for (const b of this.bodies) {
      b.vel = add(b.vel, scale(this.gravity, dt)); // semi-implicit Euler
      b.pos = add(b.pos, scale(b.vel, dt));
      this.collideWalls(b);
    }
  }

  private collideWalls(b: Body) {
    if (b.pos.x - b.radius < 0) {
      b.pos.x = b.radius;
      b.vel.x = -b.vel.x * b.bounciness;
    }
    if (b.pos.x + b.radius > this.width) {
      b.pos.x = this.width - b.radius;
      b.vel.x = -b.vel.x * b.bounciness;
    }
    if (b.pos.y - b.radius < 0) {
      b.pos.y = b.radius;
      b.vel.y = -b.vel.y * b.bounciness;
    }
    if (b.pos.y + b.radius > this.height) {
      b.pos.y = this.height - b.radius;
      b.vel.y = -b.vel.y * b.bounciness;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Notice how step remains virtually untouched from our original physics engine. All we added was the snapshot() method and the prev field. We didn't alter the math of the engine; we merely gave it a memory buffer to assist the renderer.

Now we complete the loop with snapshot(). Right before each step, we update prev:

// src/demo.ts — final tick loop inside frame()
while (acc >= STEP && steps < MAX_STEPS) {
  world.snapshot();      // prev = curr (BEFORE stepping)
  world.step(STEP);      // advance physics by fixed STEP
  acc -= STEP;
  steps++;
}
Enter fullscreen mode Exit fullscreen mode

When the while loop finishes, prev holds the position at the start of the final tick, and pos holds the position at the end of that tick. alpha tells us exactly where we stand between them.

All that remains is drawing: instead of drawing at pos, we interpolate between prev and pos by alpha.

We add a linear interpolation helper (lerp) to our vector math:

// Linear interpolation between two points by ratio t (0..1)
export const lerp = (a: Vec2, b: Vec2, t: number): Vec2 =>
  vec(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
Enter fullscreen mode Exit fullscreen mode

And update our rendering routine:

// src/demo.ts — core render logic
function render(alpha: number) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (const b of world.bodies) {
    // OFF: direct pos -> ball is locked to discrete physics ticks, producing visual jitter
    // ON:  interpolates between prev and pos by alpha -> buttery-smooth display
    const p = interpolate ? lerp(b.prev, b.pos, alpha) : b.pos;

    ctx.beginPath();
    ctx.arc(p.x, p.y, b.radius, 0, Math.PI * 2);
    ctx.fill();
  }
}
Enter fullscreen mode Exit fullscreen mode

Let me share a hesitation I had when first implementing this, because it initially confused me. Interpolation does not predict the future — it renders the past. Because we are blending between prev and pos, the ball drawn on screen is actually one physics tick behind real-time simulation state (≈16 ms at 60 Hz).

That might sound like a penalty, but 16 ms is imperceptible to human eyes, and in return, you get liquid-smooth motion. The alternative is extrapolation (predicting ahead into the future). But extrapolation during high-speed collisions is notoriously jarring: the renderer predicts the ball passing through a wall, and then snaps it backward when the collision solver resolves on the next tick. That visual popping is far worse. Almost every commercial game engine chooses interpolation. I do too.

To truly see this difference, open the interactive demo. It features a "Physics Hz" slider: intentionally drag physics down to 4 ticks per second.

With interpolation turned OFF, the ball teleports 4 times a second — choppy, jagged, and broken.

Toggle interpolation ON, and that exact same 4-tick physics suddenly glides across the screen at 60 FPS. The physics calculation underneath is 100% identical; the only difference is what your eyes perceive.


End-to-end HTML5 Canvas game loop pipeline connecting requestAnimationFrame, fixed accumulator steps, and lerp rendering
The complete HTML5 Canvas loop: clamp frameTime, snapshot and step fixed ticks, then render at interpolated coordinates.

Wiring It Together on Canvas

Let's combine all the moving parts into a single runnable loop. This is the heart of the demo — a bouncing ball, plus controls to "simulate low FPS" and "toggle interpolation":

import { vec, lerp } from "./vec";
import { World, createBody } from "./world";

const canvas = document.querySelector<HTMLCanvasElement>("#game")!;
const ctx = canvas.getContext("2d")!;

const world = new World(canvas.width, canvas.height, 900);
const ball = world.add(createBody(120, 80, 24, 0.85));
ball.vel = vec(220, 0); // initial sideways velocity

let STEP = 1 / 60; // "Physics Hz" slider changes this at runtime
const MAX_STEPS = 5;
const MAX_FRAME = 0.25;

let interpolate = true; // toggled by button
let slowMotion = false; // "simulate low FPS" — intentionally slows down frames
let acc = 0;
let last = performance.now();

function frame(now: number) {
  let frameTime = (now - last) / 1000;
  last = now;
  if (frameTime > MAX_FRAME) frameTime = MAX_FRAME;

  // To simulate low FPS, we use wall-clock time as is;
  // when slowMotion is active, we intentionally delay rendering to produce large frameTime.
  acc += frameTime;

  let steps = 0;
  while (acc >= STEP && steps < MAX_STEPS) {
    world.snapshot();
    world.step(STEP);
    acc -= STEP;
    steps++;
  }
  if (steps === MAX_STEPS) acc = 0;

  const alpha = acc / STEP;
  render(alpha);
  updateHud(frameTime, steps);

  if (slowMotion) {
    // Simulate a heavy / long frame: delay the next frame
    setTimeout(() => requestAnimationFrame(frame), 90);
  } else {
    requestAnimationFrame(frame);
  }
}

function render(alpha: number) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (const b of world.bodies) {
    const p = interpolate ? lerp(b.prev, b.pos, alpha) : b.pos;
    ctx.beginPath();
    ctx.arc(p.x, p.y, b.radius, 0, Math.PI * 2);
    ctx.fillStyle = "#e91e63";
    ctx.fill();
  }
}
Enter fullscreen mode Exit fullscreen mode

Now we bind the three interactive controls from index.html: the interpolation checkbox, the low-FPS simulator, and the "Physics Hz" slider. The slider mutates STEP dynamically at runtime — providing visual proof of our architectural thesis. We also hook up a lightweight HUD counter:

// --- Controls: the three inputs in index.html drive the live demo ---
const interpEl = document.querySelector<HTMLInputElement>("#interp")!;
const slowEl = document.querySelector<HTMLInputElement>("#slow")!;
const hzEl = document.querySelector<HTMLInputElement>("#hz")!;
const hzOut = document.querySelector<HTMLSpanElement>("#hzval")!;
const hud = document.querySelector<HTMLSpanElement>("#hud")!;

interpEl.addEventListener("change", () => (interpolate = interpEl.checked));
slowEl.addEventListener("change", () => (slowMotion = slowEl.checked));
hzEl.addEventListener("input", () => {
  const hz = Number(hzEl.value);
  STEP = 1 / hz; // readjust metronome tick interval
  hzOut.textContent = String(hz);
});

let fps = 0;
function updateHud(frameTime: number, steps: number) {
  // Smooth FPS with a simple exponential moving average
  fps += (1 / Math.max(frameTime, 1e-3) - fps) * 0.1;
  hud.textContent = `${fps.toFixed(0)} FPS • ${steps} ticks/frame`;
}

requestAnimationFrame(frame);
Enter fullscreen mode Exit fullscreen mode

The slowMotion trick is simple yet remarkably effective: setTimeout(..., 90) delays the next frame intentionally. frameTime inflates, forcing the accumulator to discharge multiple physics ticks per frame. This accurately replicates what happens on a struggling device. In this mode, turning interpolation OFF makes jitter blatantly obvious; turning it ON shows how smooth the visual experience remains.

The project runs as a single-page Vite app: npm run dev spins it up in the browser with no background Node services required.


Headless Vitest determinism verification comparing 60 FPS, 30 FPS, and 15 FPS frame schedules for bit-identical positions
Headless Vitest assertions verify identical floating-point positions across 60 FPS, 30 FPS, and 15 FPS schedules.

Proving Determinism with Automated Tests

Now let's deliver on our opening promise: same inputs yield identical state, completely independent of frame timing.

You cannot verify this inside a live browser loop: requestAnimationFrame and system timers are inherently non-deterministic.

So we extract the loop's core logic into a pure, headless Accumulator class decoupled from rAF. We feed it an array of frame durations, step the world, and inspect the final state:

import { World } from "./world";

export interface StepperOpts {
  step?: number; // fixed physics step (seconds)
  maxSteps?: number; // max ticks per frame — spiral of death protection
  maxFrame?: number; // upper bound of a single frame (seconds)
}

const EPS = 1e-9; // floating-point tolerance: avoid missing a tick at the acc == step boundary

export class Accumulator {
  acc = 0;
  readonly step: number;
  readonly maxSteps: number;
  readonly maxFrame: number;

  constructor(opts: StepperOpts = {}) {
    this.step = opts.step ?? 1 / 60;
    this.maxSteps = opts.maxSteps ?? 5;
    this.maxFrame = opts.maxFrame ?? 0.25;
  }

  advance(world: World, frameTime: number): { steps: number; alpha: number } {
    if (frameTime > this.maxFrame) frameTime = this.maxFrame;
    this.acc += frameTime;

    let steps = 0;
    while (this.acc >= this.step - EPS && steps < this.maxSteps) {
      world.snapshot();
      world.step(this.step);
      this.acc -= this.step;
      steps++;
    }
    if (steps === this.maxSteps && this.acc >= this.step - EPS) this.acc = 0;

    return { steps, alpha: this.acc / this.step };
  }
}

export function runFixed(
  makeWorld: () => World,
  frames: number[],
  opts?: StepperOpts,
): World {
  const world = makeWorld();
  const acc = new Accumulator(opts);
  for (const ft of frames) acc.advance(world, ft);
  return world;
}

// Old approach in the series — for comparison: direct step with variable dt.
export function runVariable(
  makeWorld: () => World,
  frames: number[],
  maxFrame = 1,
): World {
  const world = makeWorld();
  for (const ft of frames) world.step(Math.min(ft, maxFrame));
  return world;
}
Enter fullscreen mode Exit fullscreen mode

That EPS line is the scar of a midnight bug that cost me an hour of debugging. When doing acc += 4 * STEP and subtracting STEP four times, IEEE 754 floating-point inaccuracies occasionally left acc a microscopic hair below STEP. The loop would miss a tick — running 599 ticks instead of 600. And that broke the test. The fix is a tiny epsilon margin (- EPS) in the comparison. A subtle detail, but without it, you'd pull your hair out wondering why a frame occasionally goes missing.

Now for the definitive proof. We simulate the same 10 seconds across three radically different framerate profiles: 60 FPS, 15 FPS, and 30 FPS. We expect the fixed-timestep loop to produce bit-identical results, while the variable-dt version diverges:

import { describe, it, expect } from "vitest";
import { World, createBody } from "../src/world";
import { runFixed, runVariable } from "../src/sim";
import { lerp, vec } from "../src/vec";

const STEP = 1 / 60;
const makeWorld = () => {
  const w = new World(800, 600, 900);
  w.add(createBody(120, 80, 20, 0.8));
  return w;
};

describe("fixed-timestep loop is deterministic", () => {
  // Same 10-second total time, three different frame splits:
  const framesA = Array(600).fill(STEP);     // 60 FPS
  const framesB = Array(150).fill(4 * STEP); // 15 FPS (4 ticks per frame)
  const framesC = Array(300).fill(2 * STEP); // 30 FPS (2 ticks per frame)

  it("produces EXACTLY the same state regardless of frame timing", () => {
    const a = runFixed(makeWorld, framesA).bodies[0];
    const b = runFixed(makeWorld, framesB).bodies[0];
    const c = runFixed(makeWorld, framesC).bodies[0];

    expect(a.pos).toEqual(b.pos);
    expect(a.pos).toEqual(c.pos);
    expect(a.vel).toEqual(b.vel);
  });

  it("variable-dt version diverges (no determinism)", () => {
    // Before the first wall contact, compare in free fall: semi-implicit
    // Euler's g·dt² term yields different positions depending on dt (without settling).
    const freeA = Array(48).fill(STEP); // 0.8 s, 60 FPS
    const freeB = Array(12).fill(4 * STEP); // 0.8 s, 15 FPS
    const a = runVariable(makeWorld, freeA).bodies[0];
    const b = runVariable(makeWorld, freeB).bodies[0];

    expect(a.pos).not.toEqual(b.pos); // same total duration, different result
  });
});

describe("interpolation math", () => {
  const a = vec(0, 0);
  const b = vec(10, 20);

  it("alpha=0 yields the previous state", () => expect(lerp(a, b, 0)).toEqual(vec(0, 0)));
  it("alpha=1 yields the current state", () => expect(lerp(a, b, 1)).toEqual(vec(10, 20)));
  it("alpha=0.5 yields the exact midpoint", () => expect(lerp(a, b, 0.5)).toEqual(vec(5, 10)));
});
Enter fullscreen mode Exit fullscreen mode

The first test confirms our thesis with toEqual: at 60 FPS, 15 FPS, and 30 FPS, the ball's position and velocity vectors match down to the exact floating-point bit.

The second test proves the exact opposite: dividing the same 0.8-second free fall into different dt slices causes the variable-dt simulation to diverge (expect(a.pos).not.toEqual(b.pos)). We measure before the first wall bounce — once a ball bounces and settles on the floor, both systems come to rest in roughly the same place, but the divergence during mid-flight is undeniable due to g · dt². That two-laptop story from the introduction wasn't an illusion; it is an empirical, testable mathematical fact.

An honest engineering caveat: this determinism guarantee holds as long as you don't hit the spiral-of-death ceiling. If a frame hits MAX_STEPS and clears debt with acc = 0, you drop simulation time, and frame schedules will diverge. In our test suite, we deliberately keep frame chunks below that threshold. In a real game, you only hit that ceiling when hardware is completely choking — at which point keeping the tab responsive matters far more than bit-perfect physics synchronization.


Summary

  • Variable-dt Instability: Calling world.step(dt) with variable frame times breaks determinism due to semi-implicit Euler's nonlinear g · dt² term, and causes tunneling at low framerates.
  • The Metronome Accumulator: Store elapsed wall-clock time in an accumulator, and advance physics using invariant, fixed STEP slices (while (acc >= STEP)).
  • Taming the Spiral of Death: Protect your main thread in two steps: clamp single-frame spikes with MAX_FRAME, cap ticks per frame with MAX_STEPS, and clear accumulated debt when pegged to the ceiling.
  • Decoupled Update and Render: Physics ticks at a constant frequency; rendering runs at native display refresh rate. Forcing rendering to follow discrete physics ticks introduces temporal aliasing and micro-stutter.
  • Alpha Progress Ratio: Calculate alpha = acc / STEP to find where the renderer sits between the last completed tick and the upcoming tick.
  • Render Interpolation: Blend smoothly between previous and current positions using lerp(prev, pos, alpha). Interpolation renders 1 tick in the past (≈16ms latency) but avoids the jarring prediction snapping of extrapolation.
  • Testable Determinism: Split the same total duration into different frame slices; verify that fixed-timestep state passes toEqual while variable-dt produces not.toEqual.

Source Code & Live Demo

The complete source code — engine, game loop, interactive demo, and automated test suite — is open-source on GitHub:

📦 GitHub Repository: github.com/m2-md/fixed-timestep-render-interpolation

🎮 Interactive Live Demo: m2-md.github.io/fixed-timestep-render-interpolation

What struck me most while writing this project is an interesting architectural paradox: the very move that made the physics engine "correct" (fixed timestep) temporarily made the visuals look worse — forcing us to build an additional layer (render interpolation) to fix it. It felt like taking two steps forward and one step back. But in reality, we had previously entangled two separate concerns — simulation accuracy and display smoothness — into a single variable (dt). Once we untangled that knot, we could solve each problem on its own terms. Great architecture is often like that: decoupling two tightly wound problems so you can speak to each in its native language.

The metronome is ticking, the ball is gliding smoothly. And now, the exact same game plays identically across every machine. ⚙️🧠


📚 Canvas 2D & Game Architecture Series

👋 About the Author

I'm Mustafa Morbel, a software engineer with over 17 years of experience writing about modern web technologies, game architectures, browser rendering engines, and AI workflows.

You can inspect all codebases, runnable demos, and test suites across my GitHub profile.

For new technical guides and architectural deep dives, feel free to connect on LinkedIn and X / Twitter (@mustafamorbel).

Have you run into framerate-dependent physics anomalies or tick jitter in your own projects? I'd love to hear your thoughts in the comments below 🧠💬 — and don't forget to leave a few claps 👏 if you found this breakdown useful!


📦 Want the Bundled Starter Kit & Cheatsheets?

If you want all 3 TypeScript engines, HiDPI helpers, fixed-timestep loop templates, and vector physics cheatsheets in one clean zip, grab the TS 2D Canvas Physics & HiDPI Starter Kit (or unlock all kits free with a Buy Me a Coffee membership).

Top comments (0)