A countdown timer looks easy: call setInterval every second and subtract one. It works for a few minutes, then it starts to run slow. Here is why, and a version that stays accurate.

Why the simple version drifts

setInterval(fn, 1000) does not promise to run every 1000 ms. It promises to run no sooner than 1000 ms later. If the browser is busy, or the tab is in the background, a tick can arrive late. Browsers also throttle timers in background tabs to about once per second or even once per minute. Each late tick adds a small error, and subtracting "one second" per tick makes the error pile up.

// Drifts: assumes every tick is exactly 1 second let left = 300; setInterval(() => { left -= 1; render(left); }, 1000); 

The fix: count against the clock, not the ticks

Store the moment the timer should end. On each tick, compute what is left from the real clock.

function startTimer(seconds, onTick, onDone) { const end = Date.now() + seconds * 1000; const id = setInterval(() => { const left = Math.max(0, Math.round((end - Date.now()) / 1000)); onTick(left); if (left === 0) { clearInterval(id); onDone(); } }, 250); return () => clearInterval(id); } startTimer(300, s => console.log(s), () => console.log("Done")); 

A late tick no longer matters, because the answer comes from Date.now(). Ticking every 250 ms keeps the display from skipping a number. For a monotonic clock that ignores system clock changes, use performance.now() instead of Date.now().

Handle the background tab

When the user comes back to the tab, the next tick recalculates from the real clock, so the display jumps to the right number straight away. If you also want a sound when time is up while the tab is hidden, check the remaining time on the visibilitychange event as well, and play the sound from a user-started audio element (browsers block audio that was never started by a click).

Pause and resume

Keep the remaining milliseconds when paused, and set a new end when resuming:

let remaining = 0, end = 0, id = null; function resume() { end = Date.now() + remaining; id = setInterval(tick, 250); } function pause() { remaining = end - Date.now(); clearInterval(id); } 

Format the display

const fmt = s => String(Math.floor(s / 60)).padStart(2, "0") + ":" + String(s % 60).padStart(2, "0"); 

Try it without writing code

If you just need a timer, I keep a set of free browser timers built on this approach, from a 30 second timer and 5 minute timer to a Pomodoro timer and a general countdown timer.

(Disclosure: these timers are one of my own projects.)