Fading content using setInterval doesn't work properly when user switches tabs
I have a slideshow component that I wrote in javascript using jQuery. The slideshow consists of three slides, each containing HTML content. Each slide is a div with class .slide. Every 7 seconds, I fade out the slides that should be hidden and fade in the one I want to show. I also have some buttons (indicators) that let the user manually switch slides by clicking the buttons.
It all works great, unless the user switches tabs. If enough time elapses, when the user returns, there will be two slides visible. When the switch slide event fires, everything goes back to normal.
Example:
http://jsfiddle.net/vwdJ5/
Here is my code:
var slides = $(".slide");
var indicators = $(".indicator li");
var currentSlide = 1;
var incrementSlide = function () {
currentSlide = currentSlide === 2 ? 0 : currentSlide + 1;
};
var switchSlide = function () {
if (currentSlide === 0) {
var onDeck = 1;
var inTheHole = 2;
} else if (currentSlide === 1) {
var onDeck = 2;
var inTheHole = 0;
} else {
var onDeck = 0;
var inTheHole = 1;
}
indicators.removeClass("active");
$(indicators[currentSlide开发者_开发知识库]).addClass("active");
$(slides[onDeck]).hide();
$(slides[inTheHole]).fadeOut(200, function () {
$(slides[currentSlide]).fadeIn(200);
incrementSlide();
});
};
var interval = setInterval(switchSlide, 7000);
indicators.click(function () {
clearInterval(interval);
if ($(this).hasClass("first")) {
currentSlide = 0;
} else if ($(this).hasClass("second")) {
currentSlide = 1;
} else if ($(this).hasClass("third")) {
currentSlide = 2;
}
switchSlide();
interval = setInterval(switchSlide, 7000);
});
Modern browsers (Chrome and FF6 for sure) are now using a "queue" system on inactive tabs. You switch tabs, and setTimeout and setInterval still run, but at a much slower speed. Then when you go back to the tab, it tries to catch up, normally resulting in weird issues (sorry, probably not the most technical description).
It's recommended to use requestAnimationFrame instead if possible.
For your example where you need something to happen at specific times, you can just add stop() prior to the animations, which will prevent multiple animations from occurring at once
精彩评论