清除间隔不起作用 [英] clear interval doesn't work
问题描述
使用此代码制作幻灯片动画
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);
});
但是当我点击拇指时,计时器只会加速,这意味着clearInterval不起作用 当我尝试将鼠标悬停清除它时,也会发生这种情况
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
推荐答案
这是范围问题.
我想您尝试清除计时器时未定义计时器(尝试使用console.log()
查看).
I guess timer is undefined when you try to clear it (try to see with console.log()
).
之所以加速,是因为自clearInterval
为undefined
的值后,您什么都不清除,并且一次运行了2个间隔.
It accelerate because since you clearInterval
on undefined
value you clear nothing, and you have 2 interval running at once.
在$(document).ready
范围之外定义您的第一个timer
变量.
Define your first timer
var outside the $(document).ready
scope.
var timer;
$(document).ready(function() {
/* slider initiate */
timer = setInterval(slider,5000);
});
此外,请勿在slider
函数内重新定义var timer
.只需重新使用您之前声明的内容即可.
Also, don't re-define var timer
inside the slider
func. Just re-use the one you declared before.
但首先,请勿在slide
中重复使用setInterval
.您在另一个间隔内启动一个间隔.如果需要再次设置,请使用setTimeout
.
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.
结论
这就足够了.使用setTimeout
,您无需取消它,因为它仅触发一次.在需要时设置另一个超时,它将模拟setInterval
而不需要取消它.
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);
}
这篇关于清除间隔不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!