Set timers for upcoming milestones or deadlines to keep track of tasks.
When building a timer, the most obvious JavaScript approach is to use setInterval() to subtract 1 second every 1,000 milliseconds. But if you rely on this, your timer will inevitably break.
To save battery and CPU power, modern browsers (Chrome, Safari, Firefox) aggressively throttle JavaScript execution when a tab is put in the background. A setInterval designed to fire every 1 second might be throttled by the browser to fire only once every 10 seconds, or even 1 minute.
If your timer logic relies on subtracting 1 second every time the interval fires, a 10-minute timer might actually take 20 minutes to finish if the user switches tabs!
To fix this, professional timers never trust the interval tick. Instead, they calculate time using Delta-Time against the system clock.
When the timer starts, the code records the exact Target End Time (Date.now() + duration). Every time the screen updates (using requestAnimationFrame), it simply calculates Target End Time - Date.now(). Even if the browser pauses the tab for 5 minutes, the moment the tab is opened again, the timer calculates the exact mathematically correct remaining time instantly.
Why is it dangerous to rely purely on setInterval() for a precise countdown timer on the web?