I run a small tools site, and one of the tools is a Pomodoro timer. For a while it had a bug I didn't notice, because I only ever tested it while staring at it.
You start a 25-minute focus session, switch to your editor, and work. The whole point of a Pomodoro timer is that you aren't looking at it. But when you came back to the tab, the timer was still going. Sometimes a minute behind, sometimes a lot more.
The code looked like what most of us would write:
let secondsLeft = 25 * 60 ;
const id = setInterval ( ( ) => { secondsLeft -= 1 ; render ( secondsLeft ) ; if ( secondsLeft === 0 ) { clearInterval ( id ) ; playSound ( ) ; } } , 1000 ) ;
Enter fullscreen mode
Exit fullscreen mode
Nothing wrong with it on paper. The problem is the assumption hiding in it.
setInterval doesn't actually run every second
That code assumes the callback fires exactly once a second.…