Pause & visibilitychange
Players get interrupted: a phone rings, a colleague walks in, a notification pulls them to another tab. A good game pauses when asked (P or Esc) and also pauses by itself when the player can no longer see it. This lesson adds a proper pause state and explains what browsers do to games that run in background tabs.
What browsers do to hidden tabs
| Situation | What happens |
|---|---|
| Tab hidden (another tab, minimised window) | requestAnimationFrame callbacks stop completely |
| Hidden tab, timers | setTimeout/setInterval are throttled to about once per second, and much more after a few minutes |
| Tab visible again | rAF resumes; the first frame sees a huge time gap since the last one |
| Window loses focus but stays visible | Nothing stops: the game keeps running behind the other window |
So the browser already stops your rendering, but two problems remain. First, the time gap: if your loop computes dt from timestamps, the first frame after returning can have dt = 30 seconds, and the game simulates that half-minute in one go: enemies teleport, bullets pass through walls. Second, a game that keeps running while the window is visible but unfocused can kill the player while they type in another window.
Clamp delta time
The play kit in this course clamps the frame time: Math.min((now - last) / 1000, 0.1). Here is why that matters, with a ball heading for a thin wall:
// A ball 20 px left of a 10 px wall, moving right at 300 px/s.
function simulate(gapSeconds, clamp) {
const dt = clamp ? Math.min(gapSeconds, 0.1) : gapSeconds;
let x = 380;
const WALL_LEFT = 400, WALL_RIGHT = 410;
x += 300 * dt;
const hit = x >= WALL_LEFT && x <= WALL_RIGHT;
return `x=${x.toFixed(0)} ${hit ? 'hit the wall' : x > WALL_RIGHT ? 'TUNNELLED through' : 'not there yet'}`;
}
console.log('normal frame (1/60 s):', simulate(1 / 60, false));
console.log('2 s gap, no clamp: ', simulate(2, false));
console.log('2 s gap, clamped: ', simulate(2, true));
// With a fixed-step accumulator, a big gap means many updates in one frame.
const STEP = 1 / 60;
const updatesFor = (gap) => Math.floor(gap / STEP + 1e-9);
console.log('updates needed after a 30 s gap:', updatesFor(30));
console.log('updates after clamping to 0.1 s:', updatesFor(Math.min(30, 0.1)));normal frame (1/60 s): x=385 not there yet
2 s gap, no clamp: x=980 TUNNELLED through
2 s gap, clamped: x=410 hit the wall
updates needed after a 30 s gap: 1800
updates after clamping to 0.1 s: 6
1,800 updates in one frame would freeze the tab for a moment, and if each update takes longer than real time, the game never catches up (the "spiral of death"). Clamping trades a tiny slow-down after a hitch for stability.
Listening for visibility
The Page Visibility API fires visibilitychange on document whenever the page becomes hidden or visible; document.hidden (or document.visibilityState === 'hidden') tells you which. Pausing on hidden is the main use. Pausing on the window's blur event also covers the "visible but unfocused" case.
document.addEventListener('visibilitychange', () => {
if (document.hidden) pause('tab hidden');
});
addEventListener('blur', () => pause('window lost focus'));Note: Don't unpause automatically when the page becomes visible again. The player may not be ready; let them press a key.
Playable demo
The demo below counts "play time" only while the game is running. Press P or Esc to pause. Click outside the frame, or switch to another tab and back: the game pauses itself and tells you why.
<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 ----
let paused = false, reason = '', played = 0, autoPauses = 0;
const ball = { x: 100, y: 100, vx: 160, vy: 120 };
const paddle = { x: 200, w: 80 };
function pause(why) {
if (paused) return;
paused = true;
reason = why;
if (why !== 'P / Esc') autoPauses++;
}
document.addEventListener('visibilitychange', () => { if (document.hidden) pause('the tab was hidden'); });
addEventListener('blur', () => pause('the window lost focus'));
cv.addEventListener('blur', () => pause('the game lost focus'));
function update(dt) {
if (pressed.has('KeyP') || pressed.has('Escape')) {
if (paused) paused = false; else pause('P / Esc');
return;
}
if (paused) return; // nothing moves while paused
played += dt;
if (keys.has('ArrowLeft')) paddle.x -= 260 * dt;
if (keys.has('ArrowRight')) paddle.x += 260 * dt;
paddle.x = Math.max(0, Math.min(W - paddle.w, paddle.x));
ball.x += ball.vx * dt;
ball.y += ball.vy * dt;
if (ball.x < 6 || ball.x > W - 6) ball.vx = -ball.vx;
if (ball.y < 6) ball.vy = Math.abs(ball.vy);
if (ball.y > H - 26 && ball.y < H - 14 && ball.x > paddle.x && ball.x < paddle.x + paddle.w) ball.vy = -Math.abs(ball.vy);
if (ball.y > H + 10) { ball.x = W / 2; ball.y = 60; }
}
function draw() {
ctx.fillStyle = '#102027';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#80deea';
ctx.fillRect(Math.round(paddle.x), H - 20, paddle.w, 8);
ctx.fillStyle = '#fff';
ctx.beginPath(); ctx.arc(ball.x, ball.y, 6, 0, Math.PI * 2); ctx.fill();
ctx.font = '12px monospace';
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
ctx.fillText(`played ${played.toFixed(1)} s auto-pauses ${autoPauses}`, 8, 16);
if (paused) banner('PAUSED', `because ${reason === 'P / Esc' ? 'you pressed P / Esc' : reason}. Press P to resume`);
}
run(update, draw, 'Left/Right move, P or Esc pauses');
</script>Clicking outside the frame both blurs the canvas (the play kit then shows "Click to play") and pauses the game. When you click back in, the game is still paused and waits for P: the player decides when the action restarts.
What a pause should do
- Stop
updatebut keep drawing, so menus and the "Paused" banner stay visible. - Freeze game timers too. If you measure cooldowns with timestamps (
now - lastShot), a pause breaks them; counting down withdtinsideupdate(as this course does) pauses them automatically. - Mute or duck the sound (
audioCtx.suspend()/resume()for Web Audio). - Release held keys: a key released while paused never sends
keyupto a hidden page. The kit clearskeyson blur for this reason. - Offer the pause menu: resume, settings, restart, quit to title.
Tip: Multiplayer games can't pause the world for one player. They keep simulating and only show a menu over it; the "pause" is purely local.
Test yourself
What happens to requestAnimationFrame callbacks when the tab is hidden?
- They run at 60 FPS as usual
- They stop until the tab is visible again
- They run once per minute
- They throw an error
Why clamp dt to something like 0.1 s?
- To make the game run faster
- A huge gap after a hidden tab would teleport objects or force thousands of catch-up updates
- Because rAF requires it
- To save memory
Which event tells you the page became hidden?
unloadon windowvisibilitychangeon document, then checkdocument.hiddenresizeon windowpointerleaveon the canvas