Timers stopping or acting erratically is a common problem that occurs when you have multiple browser tabs open. Your application’s timers will stop if the page isn’t active, which can often cause bugs that are difficult to track.
Why it happens
The reason this happens is due to timer throttling. When application’s tab is inactive, most browsers will throttle tab activities to preserve resources and battery life on the user’s device.
Browser throttling affects timers, audio, video, and other APIs. So if your timer function is set to run every second, it may only run once every few seconds or even minutes when the tab is inactive.
So how can you fix it? Meet Web Workers .
Web Workers allow you to run a script operation on a different thread from your application’s main execution thread.
The timer will continue counting down even when your application’s tab becomes inactive. All major browsers support web workers, so you don’t have to worry about compatibility.
Here’s a list of all the browser APIs supported by the web workers.
Steps to fix timer problem
Now that we understand what the problem is and how web workers can help, we can move on to fixing it.
The script overrides
setTimeout, and other methods to make sure they run in the background which, in turn, will prevent them from getting throttled when the tab becomes inactive.
Setting it up is pretty straightforward. All you need to do is copy
HackTimerWorker.js to your project. Then you need to import the HackTimer.js script at the top level of your application, as follows:
import HackTimer from "./scripts/hacktimer/HackTimer";
HackTimer.js contains an
that will automatically get invoked. The IFFE will override the timer functions in the
window scope with its own implementation that uses web workers.
Once you’ve imported the script, the timers will continue working correctly even when your tab becomes inactive.
And that’s all there’s to it!
If you’d like to get more web development, React and TypeScript tips consider
following me on Twitter,
where I share things as I learn them.