I run a small tools site, and one of the tools is a Pomodoro timer. For a while it had a bug I didn't notice, because I only ever tested it while staring at it.
You start a 25-minute focus session, switch to your editor, and work. The whole point of a Pomodoro timer is that you aren't looking at it. But when you came back to the tab, the timer was still going. Sometimes a minute behind, sometimes a lot more.
The code looked like what most of us would write:
let secondsLeft = 25 * 60;
const id = setInterval(() => {
secondsLeft -= 1;
render(secondsLeft);
if (secondsLeft === 0) {
clearInterval(id);
playSound();
}
}, 1000);
Nothing wrong with it on paper. The problem is the assumption hiding in it.
setInterval doesn't actually run every second
That code assumes the callback fires exactly once a second. The browser never promised that, and in a hidden tab it goes out of its way not to, to save battery:
- In a background tab, Chrome runs timers at most about once per second and batches them together.
- Once a page has been hidden for 5 minutes, Chrome's "intensive throttling" can hold chained timers back to once a minute. That kicks in when the page is quiet, for example when it isn't playing audio.
- If the laptop goes to sleep, nothing runs at all.
- Even in the foreground, a long task on the main thread delays the callback a little, and those delays add up.
Every late or skipped tick is a second that never gets subtracted. So a 25-minute timer can easily end at 27 or 30 minutes. For a focus timer, that's exactly the case that matters.
The fix: stop counting, start comparing
The change that fixed it was small. Instead of storing how many seconds are left, store when the timer should end, and work out what's left from the real clock every time:
const DURATION = 25 * 60 * 1000;
let endAt = Date.now() + DURATION;
function tick() {
const left = Math.max(0, endAt - Date.now());
render(Math.ceil(left / 1000));
if (left === 0) {
clearInterval(id);
playSound();
}
}
const id = setInterval(tick, 250);
tick();
Now the interval is just a refresh rate. If the browser skips a whole minute of ticks, the next tick still shows the right number, because Date.now() kept moving the whole time. The timer can't drift any more. The worst it can do is update late.
Two small details make a real difference:
-
Tick faster than once a second. With exactly 1000ms, a tick that lands just after a second boundary makes the display jump from
4:32to4:30. 250ms makes that go away. -
Round up for display.
Math.ceilkeeps0:01on screen until the time is really up. WithMath.flooryou stare at0:00for almost a full second before anything happens, which feels broken.
Pausing
Pausing is the one place you need to keep a remaining time around. Save what's left, clear the end time, and rebuild it on resume:
let endAt = null; // set while running
let leftMs = DURATION; // used while paused
function start() {
endAt = Date.now() + leftMs;
}
function pause() {
leftMs = Math.max(0, endAt - Date.now());
endAt = null;
}
When the tab comes back
Even with the fix, a throttled tab might not get its next tick until a minute after the deadline. So if someone comes back to the tab, check straight away instead of waiting:
document.addEventListener("visibilitychange", () => {
if (!document.hidden) tick();
});
And if they need to know on time while they're in another app, a sound in a hidden tab isn't enough. A desktop notification is far more reliable, so I added that as an option too.
Small bonus: the countdown in the tab title
Since nobody's looking at the page, I put the time where they can see it:
const originalTitle = document.title;
function render(seconds) {
const m = Math.floor(seconds / 60);
const s = String(seconds % 60).padStart(2, "0");
document.title = `${m}:${s} · Focus`;
}
// When the timer stops:
document.title = originalTitle;
Remember to put the original title back on every way the timer can stop. I missed the "skip" button at first, and the tab kept showing a stale countdown after you skipped a session.
Wrapping up
If you want to see it working, the Pomodoro timer on AppyGrid uses everything above. Start a session, hide the tab, and it'll still end on time. The space bar starts and pauses it.
The same bug turns up in quiz timers, auction countdowns, "your session expires in…" warnings and games. Anywhere you subtract a fixed amount on each tick, it's worth switching to an end time.
Have you been bitten by timer throttling somewhere else? I'd like to hear where.
I wrote this with help from an AI assistant for drafting and editing. The bug, the fix and the code come from my own project, AppyGrid.
Top comments (0)