setInterval not working properly on Chrome
I'd favour using setTimeout() repeatedly over using setInterval() - so many things can go wrong with setInterval() and you don't know how busy the browser is and whether the interval is realistic.
Browsers don't honour your chosen timeout or interval exactly. This is mainly for security; to prevent a flood of events from messing with the browser's ability to function normally. Chrome is better about honouring timers more accurately, though it does still slow them down significantly when a tab is in the background (see this answer), for example.
If you set a new timer with setTimeout during your existing call to slideshow.action(), then you won't get events queuing up when your browser can't quite keep up, but it will still go nice and quickly when the browser is able to do so.
You will still be able to stop the timer using the timer ID, that ID will just change often.
Chrome (and apparently the latest versions of Firefox too) reduce the speed of setInterval
when the tab is in the background to improve foreground performance. This probably matters the most when there are fast running timer-driven animations in background pages. When the page comes back to the foreground, it "tries" to catch up and runs a bunch of setInterval
calls much faster than they would normally run.
The work-arounds are:
- Lengthen the time of the
setInterval
so Chrome won't mess with it (you'd have to look up what that time is). - Stop your interval timer when the page goes in the background (no need to run slides when it's not visible anyway) - then start it up again when the page comes to the foreground.
- Use repeated
setTimeout
instead ofsetInterval
with some type of repeated setTimeout like this:
Code:
function nextSlide() {
// show next slide now
// set timer for the slide after this one
setTimeout(function() {
nextSlide(); // repeat
}, xxx)
}
Similar post here.
Most likely, you shouldn't expect setInterval to ever be accurate. If I were you, I would check that the interval is correct by comparing the previous interval time to the current one. That should make the code more robust.