All writing
JavaScriptCanvas APIGamesPerformance

A Game Loop in the Browser: Architecture Notes from Two Canvas Games

5 min read

I built two retro games — Neon Slither (snake) and Neon Car (racing) — entirely with the Canvas API, no engine. The fastest way to learn game-loop architecture is to be the engine.

The loop is a state machine plus a clock

Both games share the skeleton: start → playing → over, driven by requestAnimationFrame with a delta-time step. Delta time, not frame counting, is what keeps speed identical on a 60Hz laptop and a throttled phone.

let last = performance.now();
function frame(now) {
  const dt = Math.min((now - last) / 1000, 0.05); // clamp: tab-switch spikes
  last = now;
  if (state === 'playing') { update(dt); draw(); }
  animId = requestAnimationFrame(frame);
}

That Math.min clamp matters more than anything else in the loop: after a background tab wakes up, dt can be seconds, and every car on the canvas teleports through walls. Clamp, then move on.

Lessons that generalise beyond games

A game loop is just an event system with opinions about time. The opinions are the hard part.

Need this kind of thinking on your product?

I take on select freelance and contract work — Next.js, Node.js, and AI-powered products.

Keep reading

Online now

Usually replies within an hour

Chat on WhatsApp1