Precise Timing in JavaScript: Lessons From Building a Stopwatch

May 1, 2026

Building a stopwatch sounds trivial. setInterval(fn, 10) and increment a counter, right? Wrong. That approach will drift within seconds.

The Drift Problem

setInterval and setTimeout are not guaranteed to fire at the exact specified time. The browser's event loop processes them "at least" after the delay, but CPU load, tab throttling, and garbage collection can cause significant drift.

A stopwatch using setInterval(fn, 10) can be off by seconds after just a few minutes.

The Fix: Absolute Timestamps

Instead of incrementing a counter, capture Date.now() when the timer starts and calculate elapsed time on every tick:

const elapsed = Date.now() - startTime

This way, even if a tick fires late, the displayed time is always correct. The ticks are just for re-rendering, not for keeping time.

My Stopwatch

I built a stopwatch with millisecond precision, lap recording, and lap diffs. It uses the absolute timestamp approach so it stays accurate indefinitely.

Try it: Stopwatch

Takeaway

Never trust intervals for measuring time. Always use timestamps as the source of truth.