I've got an odd little dilemma in this jQuery slideshow plugin that I am building.
It's nothing fancy and the code I have written to date is working great however I have noticed that when I leave the site running and switch to a new tab and continue browsing the web in this other tab (Chrome for Mac in my case) that when I return to my site, the setTimeout
call seems to have speed up and instead of waiting for the timer to finish the fire the event, it fires continuously.
Here is my (simplified) code:
var timer;
var counter;
var slides; // collection of all targeted slides.
// animate to the next slide
function nextSlide() {
// stop timer
methods.stopTimer();
// increase counter
counter++;
if ( counter > slides.length-1 ) { counter = 0; } // if counter is greater than the amount of slides, back to the start.
// inner = container to be animated
// in the complete callback restart the timer.
inner.animate({
'left': '-'+slides.eq( counter ).position().left
}, {
duration : settings.animationSpeed,
easing : 'easeInOutExpo',
complete : startTimer()
});
}
// timer functions.
function startTimer() {
if ( timer === '' ) {
timer = setTimeout( function() {
nextSlide();
} , 3000 );
}
}
function stopTimer() {
clearTimeout( timer );
timer = '';
}
So what should happen is that at the end of the animation, the timer gets reattached with another setTimeout
call so that it becomes a continuous slideshow (and this works just fine until you leave the tab.
Once you leave the tab and return to the tab with slideshow it seems that the 3000 ms
timer has been reduced to invoke instantly and now the moment the animation finishes the next one starts with no delay at all.
Any ideas on why this is happening on how it can be solved would be much appreciated.
Thanks for reading,
Jannis
Next, you can pass the milliseconds parameter, which will be the amount of time JavaScript will wait before executing the code. If you omit the second parameter, then setTimeout() will immediately execute the passed function without waiting at all.
No significant effect at all, setTimeout runs in an event loop, it doesn't block or harm execution.
The clearInterval() method clears a timer set with the setInterval() method.
The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.
Some browsers (like Chrome) drastically slow down recurring timers when the tab goes inactive and then, when the tab comes active again, they try to "catch up" so that the same number of actual timer events has occurred. All I can think of as a work-around is for you to stop the slideshow entirely when the tab goes inactive and start it again when it comes active.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With