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(); 

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 

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² 

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) 

Second half-step:

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

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 -| 

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); 

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); } 

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 

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 ] 

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; } } } 

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++; } 

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); 

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(); } } 

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 Source:https://dev.to/mkare/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-1f7h

Related posts