Most timer bugs people talk about are about drift or throttling. This post is about a different failure: the page stops running entirely, then comes back later, or never comes back at all. Browsers do this on purpose to save memory, battery, and CPU, and there are a few events you can use to survive it.
The states that matter
Chrome's Page Lifecycle documentation describes a page moving through these states: active, passive, hidden, frozen, terminated, and discarded. Three of them matter for anything that tracks time:
-
Hidden. The user switched tabs, minimized the window, or moved to another app on mobile. MDN's
visibilitychangereference says the move to hidden "is the last event that's reliably observable by the page," and recommends treating it as the likely end of the session. - Frozen. Chrome's guide says that in this state "the browser suspends execution of freezable tasks," which means "JavaScript timers and fetch callbacks don't run." The same thing happens to a page held in the back/forward cache. The web.dev article on bfcache explains that browsers "pause any pending timers or unresolved promises" for cached pages.
- Discarded. The browser unloads the page to free memory. According to the Chrome guide, "No tasks, event callbacks, or JavaScript of any kind can run in this state," and the discard itself fires no event. The tab title and favicon often stay visible, so to the user it looks like your page is still open.
The freeze and discard behavior comes from the WICG Page Lifecycle draft, a Draft Community Group Report dated 9 June 2022. It is not a W3C standard, and the freeze, resume, and document.wasDiscarded APIs are Chromium features. Treat them as extras. Everything below still works without them.
What breaks
Picture a countdown whose state lives only in memory: a setTimeout for the end, plus a variable holding the time remaining.
- Frozen or cached: the pending timeout is paused. When the page resumes, the callback can fire late, and an in-memory "remaining" value is stale by however long the page sat frozen.
- Discarded: memory is gone. When the user comes back to the tab, the browser reloads the page from scratch. Without saved state, the countdown starts over or is simply lost.
-
Closed on mobile: Chrome's guide notes that when users close the tab or the browser app on mobile,
beforeunload,pagehide, andunloadmay not fire. Saving state in those handlers alone loses data.
A four-step pattern
1. Save at hidden, not at unload
Write the minimum you need to rebuild the timer, which is the end time as a wall-clock timestamp plus a status, every time the page becomes hidden. Chrome's guide recommends persisting view state to sessionStorage "that you'd want restored if the page were discarded and reloaded later."
const KEY = 'countdown-state';
function saveState(state) {
// state: { endsAt: number (epoch ms), status: 'running' | 'paused' | 'done' }
sessionStorage.setItem(KEY, JSON.stringify(state));
}
function persistIfHidden() {
const hidden = document.visibilityState === 'hidden';
if (hidden && currentState) saveState(currentState);
}
document.addEventListener('visibilitychange', persistIfHidden);
Save on every Start, Pause, and Reset as well, so a crash between visibility changes doesn't lose the latest action.
2. Rebuild on load, and note whether it was a discard
function restoreState() {
const raw = sessionStorage.getItem(KEY);
if (!raw) return null;
const state = JSON.parse(raw);
if (state.status === 'running' && Date.now() >= state.endsAt) {
state.status = 'done'; // it finished while the page wasn't running
}
return state;
}
let currentState = restoreState();
if ('wasDiscarded' in document && document.wasDiscarded) {
// Chromium only: the tab was discarded while hidden and has just reloaded.
// Useful for telling the user, not required for correctness.
}
MDN notes that sessionStorage is partitioned by origin and by tab and "survives over page reloads and restores," so two tabs running the same page keep separate countdowns.
3. Recompute on bfcache restore
A page restored from the back/forward cache does not run its load code again. web.dev says pageshow fires on the initial load "and any time the page is restored from bfcache," with event.persisted set to true for the restore case.
window.addEventListener('pageshow', (event) => {
if (event.persisted && currentState) {
rescheduleFrom(currentState); // recompute remaining from endsAt, reset the timeout
}
});
rescheduleFrom stands in for your own code. It should clear any old timeout, compute endsAt - Date.now(), and either schedule a fresh timeout or go straight to the finished state.
4. Optionally handle freeze and resume
In Chromium you can listen for freeze and resume on document. Chrome's guide recommends stopping timers and closing connections on freeze. Since step 1 already saved state at hidden, which comes before frozen, the main job here is clearing stale timeouts on freeze and calling rescheduleFrom again on resume.
What this pattern can't do
None of these events let code run while a page is frozen or discarded. If a countdown ends during that time, the page can't play a sound or update the screen at that moment. All it can do is notice afterward, once the page runs again, that the end time has passed, and show that clearly. For an alert that must go off on schedule while the tab sleeps, you need something outside the page's own event loop, and that's a separate topic.
So a timer page can promise to remember when it ends and to report correctly when you come back. It can't promise to wake itself up.
Sources
- Chrome for Developers, Page Lifecycle API: https://developer.chrome.com/docs/web-platform/page-lifecycle-api
- web.dev, "Back/forward cache" article
- MDN Web Docs,
visibilitychangeevent,pageshowevent,pagehideevent, andWindow: sessionStoragereferences - WICG, Page Lifecycle, Draft Community Group Report, 9 June 2022
Top comments (0)