DEV Community

GoToolsOnline
GoToolsOnline

Posted on

Why your setInterval timer drifts in background tabs

If you've built a countdown or Pomodoro timer with setInterval that decrements a counter every second, you've probably seen it: switch tabs for 25 minutes, come back, and the timer says there are still several minutes left.

What's happening

Browsers throttle timers in hidden tabs to save battery. In Chrome, timers in a background tab run at most about once per second, and after a few minutes of being hidden, chains of timers can be limited to roughly once per minute ("intensive throttling"). Safari and Firefox have their own versions. Your callback still runs, just late, and every late tick is a second you never count.

So this pattern is broken:

let remaining = 25 * 60;
setInterval(() => {
  remaining -= 1; // assumes exactly 1000 ms passed. It didn't.
  render(remaining);
}, 1000);
Enter fullscreen mode Exit fullscreen mode

The fix: measure, don't count

Store when the timer should end, and on every tick compute the remaining time from the clock:

const endAt = performance.now() + 25 * 60 * 1000;
function tick() {
  const remainingMs = Math.max(0, endAt - performance.now());
  render(Math.ceil(remainingMs / 1000));
  if (remainingMs > 0) setTimeout(tick, 250);
  else onDone();
}
tick();
Enter fullscreen mode Exit fullscreen mode

Now a throttled tick just updates the display late; the time itself is never wrong. Also re-render on visibilitychange so the display is correct the moment the user comes back. If the timer must survive a reload, save a wall-clock end time (Date.now()) in localStorage instead, since performance.now() resets per page.

The sound problem

The other trap is the alarm. Firing audio.play() from a throttled timer can be a minute late. One approach is to schedule the sound ahead of time on the Web Audio clock (AudioContext.currentTime) when the timer starts, after a user gesture has unlocked audio. A desktop notification is a useful backup for when the tab is in the background.

Summary

  • Never decrement a counter per tick; compute from an end timestamp.
  • Re-render on visibilitychange.
  • Schedule end sounds in advance rather than from the last tick.

Disclosure: I run GoToolsOnline, and I rebuilt its Pomodoro timer around exactly these fixes after the old version drifted in background tabs. You can see it here: https://gotoolsonline.com/tools/pomodoro-timer

Top comments (0)