Why JavaScript setInterval Countdown Timers Drift and How to Keep Them Accurate
A common approach to countdown timers, calling setInterval every second and subtracting one, gradually falls behind over time. The reason is that setInterval only guarantees a callback runs no sooner than the delay, so busy browsers and background-tab throttling can make ticks late, and those small errors accumulate. The article proposes storing the target end time and recomputing the remaining seconds from the real clock on each tick, polling every 250 ms so the display never skips a number. It also covers using performance.now() for a monotonic clock, recalculating when a hidden tab becomes visible again, and handling pause and resume by saving the remaining time. The author notes at the end that they maintain a set of free timers built on this method.
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