Slow timer with Pomodoro React App

i’m making a pomodoro app with React and the timer works fine when I’m on the tab but when i go to another tab the timer gets slower a bit.
I’m using a setInterval with 1000 ms to update the timer and I thought time would run normally even when the tab was inactive.
Is there something I’m missing to fix this?

Code Link (with deploy link in there)

1 Like

The problem is that setInterval isn’t really all that accurate. It does not guarantee that it fires exactly every 1000ms. It makes a best attempt to do so, but if you have a lot of other things going on in your browser then it will be delayed (as you have noticed).

I’m sure if you google for something like “create an accurate timer with javascript” you will find a lot of suggestions on how to make your timer more accurate.

2 Likes

thank you i’ll search for other options

2 Likes

There is throttling implemented by the browsers.

MDN: Timeouts in inactive tabs


Never tried it but you can use Web Workers for the timers. Here is an npm package that implements the timer functions using Web Workers. There might be React-specific packages that use something similar but I didn’t look for it.

Playing a sound at least every 30 seconds should also prevent the browser from throttling. This might be an easy option and it still fits with the app (like a sound to indicate the timer is running would make sense).

1 Like

This is what I would recommend. I used them in my drum machine app to get precision timing with the sequencer and it worked great.

1 Like

Thank you guys for the alternatives.
The solution i found was using Date.now() to measure the real interval between setIntervals activation and subtract that from the timer.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.