The Background-Tab Bug I Missed in My JavaScript Polling Code
I thought replacing setInterval() with recursive setTimeout() had made a polling loop safe. Only one request would run at a time, and I cleared the next timeout when the page became hidden. It still had a race. The timeout was gone. The request already in flight was not. If the page became visible again before that old request finished, a new polling run could start. The old response could then…
The issue with JavaScript polling code is that replacing setInterval() with recursive setTimeout() did not fully ensure safe execution. Although only one request would run at a time, and the next timeout was cleared when the page became hidden, there was still a race condition. If the page became visible again before the old request finished, a new polling run could start, potentially overwriting fresher state with an old response.
Clearing the timeout with clearTimeout() did not protect the UI from this problem. The race condition was more dangerous than the previously investigated timer drift. To fix this issue, three separate decisions were required: timestamps to measure elapsed time, visibility changes triggering resynchronization, and cancellation along with a run identifier to prevent stale requests from updating state.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.