
Building a Reliable Browser Stopwatch Is Harder Than You Think
I needed a simple stopwatch in the browser for timing user interaction flows during usability testing. I thought it would take 10 minutes to build. It took two days to get right, and the reason is that JavaScript timers are fundamentally unreliable for precision timing. The problem with setInterval The naive approach is obvious: let elapsed = 0 ; const interval = setInterval (() => { elapsed += 10 ; display ( elapsed ); }, 10 ); This looks like it increments every 10 milliseconds. It does not. setInterval guarantees a minimum delay of 10ms, not an exact delay. The actual interval depends on the browser's event loop, current tab focus state, CPU load, and garbage collection pauses. On a busy page, a "10ms" interval might fire every 14-20ms. Over 60 seconds, that drift accumulates to several seconds of error. Your stopwatch shows 60 seconds, but 63 seconds have actually passed. The correct approach: wall clock timestamps Instead of counting intervals, you record the start time and comput
Continue reading on Dev.to Webdev
Opens in a new tab




