[英]How do I properly restart a timeout in Javascript?
我有一个幻灯片旋转木马,我以5秒的间隔旋转。 我有一个函数,可以清除超时以停止旋转。 我正在尝试使用下面的代码重新启动轮播。 行为有效,但不正确。 它不是以5秒的间隔恢复,而是快速闪过幻灯片。
t = setTimeout(carousel, 5000);
var interval;
$(document).on('mousemove keyup keypress',function(){
clearTimeout(carousel);
setTimeout(carousel, 6000);
})
我认为你正在清除inproper变量的超时。 根据文档,它应该是超时的id,所以:
t = setTimeout(carousel, 5000);
$(document).on('mousemove keyup keypress',function(){
clearTimeout(t);
t = setTimeout(carousel, 6000);
}
这个
clearTimeout(carousel);
是不正确的。 clearTimeout
的参数不是回调函数,它是setTimeout
返回的超时标识符。 应该是这样的
t = setTimeout(carousel, 5000);
$(document).on(/* some events */,function(){
clearTimeout(t);
});
$(document).on(/* some other events */,function(){
t = setTimeout(carousel, 6000);
});
这是问题所在:
t = setTimeout(carousel, 5000);
var interval;
$(document).on('mousemove keyup keypress',function(){
clearTimeout(t /* instead of carousel */);
t = setTimeout(carousel, 6000); // also refresh the value of the timeout
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.