I am building a web app where we have a definition of session length and when the user exceeds the length we have to show a timeout popup to the user.
Currently I have a periodic timer which runs every second checking the remaining time of the session and when it hits the desired value a callback is executed. However recently got to know about the Inactive Tab throttling scenario where the running of timers is indeterministic and may not run at all for tabs in background.
Question: Once the window is brought back into focus, will the timer run again or once it hangs up, the timer does not resume again?
If the timer runs again from what time will it start to run? Are the tick events buffered in a queue or not thrown at all when the tab is in the background.
Any documentation for this would be extremely helpful.
I tried reproducing this in various ways but the results were indeterministic.
2
Answers
setTimeout
andsetInterval
are throttled in inactive tabs, but resumed normally when a tab is activated. Use dates to find the timeout:Also when the timeout happens on an active tabs you can send a message to inactive tabs immediately through
localStorage
orBroadcastChannel
so the inactive tabs could stop their timers.When it comes to handling timer events in the background, many browsers tend to restrict or completely suspend the execution of timers when a tab is idle or in the background to save system resources. As a result, timer events may be missed during this time. Specific documentation about this behavior may vary between browsers and may be subject to change with new versions. To get more detailed information about the behavior of timers in a specific browser, I recommend that you consult the official documentation of the browser or look for specific resources on the web for that specific browser and version.
Also, to manage the behavior of background timers in your specific case, you might consider using features like Web Workers, which allow you to run JavaScript code in the background on a separate thread and are not affected by the management of the browser’s main tab timers.
Here you can find more information about Web Workers:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers