clear interval doesn't work

2019-07-18 05:29发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-18 06:07

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);
 }
查看更多
登录 后发表回答