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
- Ref state for the loop, React state for the HUD — putting score updates through React renders at 60fps is a trap I walked into once.
- Resize the canvas to devicePixelRatio or your neon glow becomes neon blur on retina screens.
- Collision first, visuals second: a simple AABB pass kept the racing game honest before any pixel-perfect work — and pixel-perfect was never needed.
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.