Debugging & Performance
Game bugs are slippery: they last one frame, depend on timing and vanish the moment you add a console.log. You fight them by making the invisible visible (hitboxes, velocities, timings), by controlling time (freeze, step, slow motion) and by making runs repeatable, so a bug you saw once can be replayed on demand. This lesson builds those tools into a small game and then looks at the browser's own profilers.
A debug overlay you can toggle
Every serious game has a key that draws the "truth" on top of the art: the collision boxes the physics really uses, which way things are moving and how long each frame took. Keep it in the shipped build, behind a key. When a player reports "the ball went through the wall", you'll want it.
The demo below has a dozen bouncing balls. Click it, then try the debug keys:
| Key | Action |
|---|---|
G |
toggle the debug overlay (hitboxes, velocity vectors, frame-time graph) |
P |
freeze the simulation |
N |
step one update while frozen |
T |
slow motion (¼ speed) on/off |
<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; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set(); // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
ctx.save();
ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
ctx.restore();
}
function run(update, draw, help = '') {
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (active) {
acc += dt;
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
draw();
} else if (!idleDrawn) {
draw(); banner('Click to play', help); idleDrawn = true;
}
requestAnimationFrame(frame);
});
}
// ---- end of play kit ----
// A seeded random generator: the same seed gives the same balls every run.
function mulberry32(seed) {
return () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const rnd = mulberry32(7);
const balls = Array.from({ length: 12 }, (_, i) => ({
id: i, r: 8 + rnd() * 10,
x: 40 + rnd() * 400, y: 40 + rnd() * 190,
vx: (rnd() - 0.5) * 260, vy: (rnd() - 0.5) * 260,
color: `hsl(${Math.floor(rnd() * 360)} 70% 60%)`,
}));
const debug = { overlay: false, frozen: false, slow: false };
const frameTimes = []; // the last 120 frame times in ms
let lastFrame = performance.now();
function update(dt) {
if (pressed.has('KeyG')) debug.overlay = !debug.overlay;
if (pressed.has('KeyP')) debug.frozen = !debug.frozen;
if (pressed.has('KeyT')) debug.slow = !debug.slow;
if (pressed.has('KeyC')) console.table(balls.map(({ id, x, y, vx, vy }) => ({ id, x: Math.round(x), y: Math.round(y), vx: Math.round(vx), vy: Math.round(vy) })));
const step = pressed.has('KeyN');
if (debug.frozen && !step) return; // frozen: only N advances time
const t = debug.slow ? dt / 4 : dt; // slow motion = scaled dt
for (const b of balls) {
b.x += b.vx * t;
b.y += b.vy * t;
if (b.x < b.r) { b.x = b.r; b.vx = Math.abs(b.vx); }
if (b.x > W - b.r) { b.x = W - b.r; b.vx = -Math.abs(b.vx); }
if (b.y < b.r) { b.y = b.r; b.vy = Math.abs(b.vy); }
if (b.y > H - b.r) { b.y = H - b.r; b.vy = -Math.abs(b.vy); }
}
}
function draw() {
const now = performance.now();
frameTimes.push(now - lastFrame);
if (frameTimes.length > 120) frameTimes.shift();
lastFrame = now;
ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
for (const b of balls) {
ctx.fillStyle = b.color;
ctx.beginPath(); ctx.arc(b.x, b.y, b.r, 0, Math.PI * 2); ctx.fill();
}
ctx.fillStyle = '#9aa3b5'; ctx.font = '12px monospace'; ctx.textAlign = 'left';
ctx.fillText(`G overlay P freeze N step T slow C table${debug.frozen ? ' [FROZEN]' : ''}${debug.slow ? ' [SLOW]' : ''}`, 8, H - 8);
if (debug.overlay) drawDebug();
}
function drawDebug() {
ctx.lineWidth = 1;
for (const b of balls) {
ctx.strokeStyle = '#00e676'; // the hitbox the code really uses
ctx.strokeRect(b.x - b.r, b.y - b.r, b.r * 2, b.r * 2);
ctx.strokeStyle = '#ffeb3b'; // velocity: where it goes in 0.2 s
ctx.beginPath(); ctx.moveTo(b.x, b.y); ctx.lineTo(b.x + b.vx * 0.2, b.y + b.vy * 0.2); ctx.stroke();
ctx.fillStyle = '#fff'; ctx.font = '10px monospace';
ctx.fillText(b.id, b.x + b.r + 2, b.y - b.r);
}
// Frame-time graph: one bar per frame, the red line is the 60 FPS budget (16.7 ms).
const gx = W - 130, gy = 10, gh = 50;
ctx.fillStyle = 'rgba(0,0,0,0.7)'; ctx.fillRect(gx - 4, gy - 4, 128, gh + 22);
frameTimes.forEach((ms, i) => {
const h = Math.min(ms, 50);
ctx.fillStyle = ms > 17.5 ? '#ff5252' : '#69f0ae';
ctx.fillRect(gx + i, gy + gh - h, 1, h);
});
ctx.strokeStyle = '#ff5252';
ctx.beginPath(); ctx.moveTo(gx, gy + gh - 16.7); ctx.lineTo(gx + 120, gy + gh - 16.7); ctx.stroke();
const avg = frameTimes.reduce((s, x) => s + x, 0) / frameTimes.length;
ctx.fillStyle = '#fff'; ctx.font = '11px monospace';
ctx.fillText(`${(1000 / avg).toFixed(0)} FPS ${avg.toFixed(1)} ms`, gx, gy + gh + 13);
}
run(update, draw, 'G overlay · P freeze · N step · T slow motion');
</script>Things to notice:
- Freeze and step live inside
update, not around the loop. The game keeps drawing while frozen, so the overlay stays readable, andNruns exactly one fixed step, so you can walk through a collision frame by frame. - Slow motion is just a smaller
dt. Because all movement isvelocity * dt, scalingdtslows the whole world consistently. (Hit-stop in Screen Shake & Hit Stop uses the same trick.) Cprints aconsole.tableof every ball. The lesson shows it under the frame; in DevTools you get a sortable table. Tables beatconsole.logfor "which of these 50 enemies has a NaN position?".- The overlay draws the hitbox the code uses (here a square around each circle), not the sprite. Many "unfair" deaths are a hitbox bigger than the art.
Tip: Make debug keys edge-triggered (
pressed, notkeys). A heldGthat toggles every update flickers the overlay 60 times a second.
Measuring frames, not guessing
A frame-time graph tells you more than an FPS number. An average of 60 FPS can hide a 90 ms hitch every few seconds, and that hitch is what players feel as "stutter". Studios report the average, the 95th/99th percentile and the worst frame, plus how many frames missed the budget. This function does exactly that for a list of frame times (here a recorded sample with two hitches):
function frameStats(times, budget = 1000 / 60) {
const sorted = [...times].sort((a, b) => a - b);
const pick = (p) => sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))];
const avg = times.reduce((s, t) => s + t, 0) / times.length;
return {
frames: times.length,
avgMs: +avg.toFixed(2),
fps: Math.round(1000 / avg),
p95: pick(0.95),
p99: pick(0.99),
worst: sorted[sorted.length - 1],
overBudget: times.filter((t) => t > budget + 1).length,
};
}
// 40 frames recorded from a game: mostly 16-17 ms, a GC pause and a level load.
const sample = [
16.6, 16.7, 16.6, 16.8, 16.7, 16.6, 16.7, 16.6, 16.7, 16.8,
16.6, 16.7, 48.2, 16.6, 16.7, 16.6, 16.7, 16.8, 16.6, 16.7,
16.6, 16.7, 16.6, 16.8, 16.7, 16.6, 16.7, 16.6, 16.7, 16.8,
16.6, 16.7, 16.6, 16.7, 91.4, 16.6, 16.7, 16.6, 16.8, 16.7,
];
console.log(frameStats(sample));{
frames: 40,
avgMs: 19.33,
fps: 52,
p95: 48.2,
p99: 91.4,
worst: 91.4,
overBudget: 2
}
Two bad frames out of forty drag the "FPS" down to 52, yet 38 frames were perfect. The percentiles and the worst frame point at the real problem: two long pauses, not a slow game. Fix spikes and averages usually take care of themselves.
Replays: make the bug happen again
The worst bug report is "it happened once". If your game is deterministic, so that the same starting state plus the same inputs always give the same result, you can record the inputs of a session and replay them to reproduce any bug exactly. That needs three things you already have in this course:
- a fixed-step update (see The Fixed-Step Loop), so physics doesn't depend on frame timing;
- a seeded random generator instead of
Math.random(); - an input log: which keys were down on which update step.
function mulberry32(seed) {
return () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// One simulation step: the player moves; enemies spawn at random x positions.
function simulate(seed, inputLog, steps) {
const rnd = mulberry32(seed);
const state = { x: 100, spawned: [], score: 0 };
for (let step = 0; step < steps; step++) {
const input = inputLog[step] ?? '';
if (input.includes('L')) state.x -= 3;
if (input.includes('R')) state.x += 3;
if (step % 10 === 0) state.spawned.push(Math.floor(rnd() * 200));
state.score += state.spawned.filter((ex) => Math.abs(ex - state.x) < 20).length;
}
return state;
}
// The recorded session: step number -> keys held.
const log = { 3: 'R', 4: 'R', 5: 'R', 12: 'L', 13: 'L', 20: 'RL', 25: 'R' };
const first = simulate(42, log, 40);
const replay = simulate(42, log, 40);
const otherSeed = simulate(43, log, 40);
console.log('first: ', JSON.stringify(first));
console.log('replay:', JSON.stringify(replay));
console.log('same? ', JSON.stringify(first) === JSON.stringify(replay));
console.log('seed 43 differs?', JSON.stringify(first) !== JSON.stringify(otherSeed));first: {"x":106,"spawned":[120,89,170,133],"score":65}
replay: {"x":106,"spawned":[120,89,170,133],"score":65}
same? true
seed 43 differs? true
In a real game you'd log { step, keys: [...keys] } whenever the held keys change, save the log with the seed when a tester presses a "report bug" key, and feed it back instead of the keyboard. The replay hits the bug on the same step every time, and you can freeze and step through it with the overlay on.
Note: Determinism breaks easily: iterating a
Setin a different order, usingdtfrom the real clock instead of the fixed step, or callingMath.random()anywhere in gameplay code. Keep cosmetic randomness (particles, screen shake) on a separate generator so it can't change gameplay.
The browser's tools
| Tool | Where | Use it for |
|---|---|---|
| Performance panel | DevTools → Performance → record 5 s of play | See each frame as a bar; long frames are flagged. Expand a frame to find the slow function (scripting) or a big paint/layout |
| Rendering drawer | DevTools → ⋮ → More tools → Rendering | "Frame Rendering Stats" shows an FPS meter on top of the page; "Paint flashing" shows what the browser repaints |
| Memory panel | DevTools → Memory → Allocation sampling or heap snapshot | Find code that allocates every frame (objects, arrays, closures, strings); compare two snapshots to find leaks |
| Performance monitor | DevTools → ⋮ → More tools → Performance monitor | Live JS heap size: a saw-tooth pattern means frequent garbage collection |
console.table, console.count, console.time |
Console | Inspect entity lists, count how often something happens per second, time a function |
Breakpoints + debugger; |
Sources panel | Pause on the exact frame. Put if (ball.x !== ball.x) debugger; (a NaN check) in update to stop when a value goes bad |
Garbage collection deserves a special mention. A game that creates a few hundred small objects per frame ({x, y} vectors, bullet objects, array.filter copies) makes the heap grow quickly, and every so often the browser pauses to clean up. That pause is the 48 ms spike in the sample above. The cure is to reuse objects instead of creating them: object pools (see Shooter 4: Object Pooling), arrays you clear with length = 0, and math that writes into existing objects.
Tip: Profile in a normal window with extensions off, and test the production build. Development tools and extensions add their own work to every frame and mislead the profiler.
A debugging checklist
- Can you see it? Turn the overlay on. Is the hitbox where you think? Is the velocity pointing where you think?
- Can you slow it down? Freeze before the bug and step frame by frame.
- Can you repeat it? Fixed step + seed + input log. Then a fix can be tested by replaying.
- Is it a number problem? Check for
NaN(division by zero when normalizing a zero vector is the classic),Infinityand hugedtvalues after a tab switch. - Is it timing? Try the game at 30 and 144 FPS (DevTools → Performance → CPU throttling slows the CPU; a 144 Hz monitor or
dtscaling tests high rates).
Test yourself
Why does the demo implement freeze and single-step inside update instead of stopping the whole loop?
- Stopping the loop is not allowed in JavaScript
- The game keeps drawing, so the debug overlay stays visible, and one key press runs exactly one fixed update
- It makes the game run faster
requestAnimationFramecannot be cancelled
A game averages 58 FPS but players complain about stutter. What should you look at?
- Only the average FPS
- The worst frames and the 95th/99th percentile frame times
- The canvas size
- The number of
console.logcalls
Which three ingredients make an input replay reproduce a bug exactly?
- A fast computer, a big canvas and WebGL
- A fixed-step update, a seeded random generator and a log of inputs per step
Math.random(),Date.now()andsetTimeout- Source maps, breakpoints and screenshots