I wrote a simple jquery slider that basically goes through 3 divs, hidding one and then fadeIn the next and so on using setInterval()
The slider works just fine for my purposes, but when I open other tabs and then come back to the page’s tab, all the divs are visible and then they start to disappear and it starts working again.
Here is my jquery, which is inside $(function(){}):
$('#slideshow-next').click(function() {
pauseSlideshow();
nextSlide();
});
$('#slideshow-prev').click(function() {
pauseSlideshow();
prevSlide();
});
$('#slideshow-pause').click(function(){
pauseSlideshow();
});
$('#slideshow-play').click(function() {
playSlideshow();
});
interval = setInterval('nextSlide()', 4000);
});
function playSlideshow() {
interval = setInterval('nextSlide()', 4000);
$('#slideshow-play').hide();
$('#slideshow-pause').show();
nextSlide();
}
function pauseSlideshow() {
interval = clearInterval(interval);
$('#slideshow-pause').hide();
$('#slideshow-play').show();
}
function nextSlide() {
//hide current slide
$('#slide'+currentSlide).hide();
// show next slide
var next = (currentSlide+1)%3;
$('#slide'+next).fadeIn('slow');
currentSlide = next;
}
function prevSlide() {
//hide current slide
$('#slide'+currentSlide).hide();
// show next slide
var next = (currentSlide-1)%3;
$('#slide'+next).fadeIn();
currentSlide = next;
}
I think you might be hitting a different case as asked on Chrome: timeouts/interval suspended in background tabs?, which states that:
So you could either code the
setIntervaldifferently How can I make setInterval also work when a tab is inactive in Chrome? or detect the tab switch to halt the slideshow and re-start on tab focus How to tell if browser/tab is activeAlso, Jquery setInterval too fast when coming from another tab may be useful as it states that