5

It appears when you minimize a window or swap tabs, JavaScript's setInterval() method starts becoming incredibly unreliable.

I just finished working on a time tracking feature on an app I'm working on, which is driven by setInterval. This all worked perfectly until I started minimizing the window and coming back to it later, only to find out that the time had increased a small fraction of what it does when the window is up on the screen.

This seems to be a browser level "feature".

Is there an easy alternative I can swap this out for where units of time are actually honoured?

JamesNZ
  • 482
  • 5
  • 17
  • Javascript continues to run in the background while the window is minimized. It can even manipulate the DOM. It is probably an issue with your code. Can we see it? – mattdevio Dec 08 '15 at 20:34
  • If the duplicate I've selected does not solve your issue, please comment with more specifics about how your issue differs, and I can reopen your question. If it *does* solve your problem, happy coding! – apsillers Dec 08 '15 at 20:49
  • @magreenberg The problem is that modern browsers limit `setInterval` to running at most once per second (or so) when the page is not visible. – apsillers Dec 08 '15 at 20:52
  • Wow, I had no idea. Good thing to know. – mattdevio Dec 08 '15 at 20:59
  • Thanks for the comments guys. I've swapped the setTimeout implementation with a web worker approach and at least over a 5~ minute timespan the issue looks like it might be resolved. I'll leave it over an hour and see if it's solved it. – JamesNZ Dec 08 '15 at 21:45
  • I found a drop in replacement for setTimeout and setInterval (https://github.com/turuslan/HackTimer). I'm giving that a try rather than building my own web worker script for the moment. – JamesNZ Dec 08 '15 at 21:46

1 Answers1

3

That seems to be a feature in some browsers such a Chrome in that tabs which are inactive/in the background are allowed a timeout period no smaller than 1000 milliseconds. You can read about it here

The common solution is to use Web Workers, as they will not be affected by this issue. In fact a few such solutions have been shown here before.

Community
  • 1
  • 1
spac3nerd
  • 176
  • 3