How a Hidden Race Condition in JavaScript Polling Can Silently Corrupt UI State
A developer discovered that replacing setInterval() with recursive setTimeout() in a polling loop did not fully eliminate race conditions in JavaScript. Even after clearing the next timeout when a browser tab became hidden, any in-flight network request could still complete after the tab regained visibility, potentially overwriting fresher data with a stale response. The fix required three coordinated changes: using timestamps to measure elapsed time, triggering resynchronisation on visibility changes, and assigning run identifiers to cancel outdated requests. Browser throttling of background timers varies by browser version, OS, power state, and audio activity, making it unreliable to count callbacks as a proxy for elapsed time. Using Date.now() to calculate actual elapsed time, rather than incrementing a counter on each callback, is the recommended approach for accurate UI updates.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in