clear interval doesn't work

a 夏天 提交于 2019-12-24 00:38:20

问题


iam using this code to animate a slideshow

$(document).ready(function() {
/* slider initiate */
var timer = setInterval(slider,5000);

});
/* slider code */

var position = 0;
function slider() {
$('.slider .thumbs a').removeClass('selected');
position += 660;

var newPosition = position * (-1) + 'px';
if (position == 1980) {
    position = 0;
    newPosition = '0px';
}
var index = position / 660;
$('.slider .thumbs a').eq(index).addClass('selected');
$('.slider .slider-container').animate({left: newPosition}, 1000);
}
    /* click animation */
$('.slider .thumbs a').click(function(){
$('.slider .thumbs a').removeClass('selected');
$(this).addClass('selected');
var index = $(this).index();
var newPosition = index * (-660) +'px';
$('.slider .slider-container').animate({left: newPosition}, 1000);
clearInterval(timer);
var timer = setInterval(slider,5000);
});

but when i click on the thumbs the timer only accelerate that means that clearInterval doesn't work that happens too when i try to clear it on hover


回答1:


It's a scope problem.

I guess timer is undefined when you try to clear it (try to see with console.log()).

It accelerate because since you clearInterval on undefined value you clear nothing, and you have 2 interval running at once.

Define your first timer var outside the $(document).ready scope.

var timer;
$(document).ready(function() {
/* slider initiate */
timer = setInterval(slider,5000);    
});

Also, don't re-define var timer inside the slider func. Just re-use the one you declared before.

But before all, don't re-use setInterval inside slide. You launch an interval within an other interval. You should use setTimeout if you need to set it again.

Conclusion

This is enough. With setTimeout you don't need to cancel it since it trigger only once. Set another timeout while you need to and it will simulate a setInterval without the need of canceling it.

$(document).ready(function() {
/* slider initiate */
    setTimeout(slider,5000);
});

 function slider() {
    // your code
    setTimeout(slider, 5000);
 }


来源:https://stackoverflow.com/questions/22665190/clear-interval-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!