Define what visibility changes
For a reflex game, pause active play when document.visibilityState changes to hidden, freeze the countdown, clear any held-key state, and show a resume affordance when visible again. A turn-based puzzle may keep its board unchanged without presenting a pause screen, while still silencing audio and resetting its animation clock.
Write down the expected behavior for a timer, a moving hazard, and a pressed key before implementation. Then switch away during each case and return. This small matrix catches bugs such as a key staying logically held or a timer expiring while the game was not visible.
Reset timing before resuming
Listen for the visibilitychange event and separate the pause decision from rendering. On return, set the previous-frame timestamp to the current animation timestamp or mark the first resumed frame as a clock reset. Otherwise the next delta may include the whole hidden interval and move objects abruptly.
Use the Page Visibility API rather than relying only on blur and focus: a window can lose focus while remaining visible, and visibility conveys whether the document is actually hidden. Keep any autosave policy independent; pause behavior and persistence have different purposes and should be tested separately.
Questions about pause browser game background tab
Will requestAnimationFrame keep running in a hidden tab?
Most browsers pause animation callbacks in background tabs or hidden iframes, and timer callbacks may also be throttled. Treat those behaviors as reasons to handle visibility rather than as a precise clock.
Should every game pause when hidden?
No single policy fits every design. Pause games where unseen simulation changes the challenge; for turn-based play, preserving the current board can be enough. In either case, reset timing and audio deliberately on return.