Menu

Why your JavaScript timer is wrong in a background tab (and the fix)
📰

Why your JavaScript timer is wrong in a background tab (and the fix)

DEV Community: frontend·AppyGrid·3 days ago
#p5iGvCkf
#devtofrontend#devto#dev#timer#tick
Long article (996 words) — no AI summary yet.
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.