🔄 Fix a Polling Loop Doubling After a Tab Regains Focus
Adding a visibilitychange listener that polls immediately when a backgrounded tab becomes visible again is a reasonable way to make a view feel fresh after a user comes back to it – but if that immediate poll doesn’t also reset the page’s existing setInterval, the original timer keeps running on its own untouched schedule. The tab regains focus, the immediate poll fires right away, and the regular interval’s own next tick – already due from before the tab was backgrounded – lands only a few seconds later, so two fetches end up overlapping, and if the poll function has no in-flight guard, both run to completion and both apply their own, possibly differently-timed, results to the UI.
🔎 The Problem
let pollTimer = setInterval(fetchUpdates, 15000);
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
fetchUpdates(); // poll immediately so the view feels fresh again
// BUG: the original setInterval(fetchUpdates, 15000) from page load
// is still running on its OWN 15-second clock, untouched - it does
// not know an extra poll just happened
}
});
// Tab backgrounded for 40s, regains focus at second 0:
// -> immediate poll fires right away (visibilitychange handler)
// -> the original interval's next tick was already due around
// second 5-10 depending on when it last fired before backgrounding
// -> two fetchUpdates() calls land within a few seconds of each other,
// and if fetchUpdates() has no in-flight guard, both run fully and
// both apply their (possibly differently-timed) results to the UI
✅ Fix: Reset the Interval on Focus
- Clear and restart the interval inside the visibilitychange handler (clearInterval the old timer, call fetchUpdates(), then start a fresh setInterval) so the immediate poll also resets the regular schedule’s clock instead of running alongside it.
- Add a simple in-flight guard inside fetchUpdates() itself so a poll triggered while a previous one is still in flight skips instead of stacking a second concurrent request.
- If the endpoint behind the poll has any non-idempotent side effect (marking something as read, incrementing a view counter, firing an analytics event), make that specific action idempotent server-side rather than relying on the client to never possibly call it twice – a fixed client bug today doesn’t protect against the next one.
🚨 Why This Is Dangerous
Two overlapping polls landing a few seconds apart from each other rarely crashes anything, which is exactly why it’s easy to ship – the visible symptom is usually just a duplicated notification or a double-counted event, and neither looks like a timer bug until someone actually goes looking for one.
A visibilitychange handler that fires an extra poll is only an optimization if it also knows about the regular poll it’s running alongside – otherwise it’s just a second, unsynchronized timer.




