-->

Simple slider with setInterval() with strange beha

2019-07-21 09:15发布

问题:

I'm trying to make simple slider by using setinterval and jquery.
you can have a look here http://jsfiddle.net/5m2Dq/
Slider works fine when it is in focus on browser but when we go to different tab for more than 5 min all the div's come's under each other, and start toggling.

$('#fbLoginSlide div:gt(0)').hide();
setInterval(function(){
   $('#fbLoginSlide :eq(0)').fadeOut('slow').hide()
   .next('div.loginSlide').fadeIn('slow')
   .end().appendTo('#fbLoginSlide');
},2000);

Is there a simple way to achieve the sliding effect like this without any plugin.

回答1:

This occurs probably because your browser starts missing timeouts. Especially if you are viewing another tab, the browser thinks that it is not important to call the callback with exactly 2 second intervals. You should ditch the setInterval function altogether! Use instead the completion callback of fadeOut and fadeIn to trigger the effects.

Try something like

var cycle = function() {
   $('#fbLoginSlide :eq(0)').fadeOut('slow').hide()
   .next('div.loginSlide').fadeIn('slow', function() { setTimeout(cycle, 1500); })
   .end().appendTo('#fbLoginSlide');
};
cycle();