High-Precision JavaScript Timers: requestAnimationFrame, performance.now, and Drift Mitigation

By Evorenza Engineering • Category: Developer Guides

Why setInterval Drifts

A common rookie mistake when building stopwatches or workout timers in JavaScript is accumulating elapsed milliseconds by incrementing a counter on each interval tick.

Because JavaScript operates on a single-threaded event loop, intervals get delayed behind DOM reflows and garbage collection. Tabs in the background are also throttled by browsers to 1000ms.

The Timestamp Delta Pattern

To construct a drift-free stopwatch, record an anchor timestamp at start and calculate elapsed time as the difference between the current performance clock and the anchor: elapsed = performance.now() - startTime.