我有一张幻灯片轮播,每隔5秒旋转一次。 我有一个清除超时以停止旋转的功能。 我正在尝试使用以下代码重新启动轮播。该行为有效,但不正确。它不再以5秒的间隔恢复,而是在幻灯片中快速闪烁。
t = setTimeout(carousel, 5000);
var interval;
$(document).on('mousemove keyup keypress',function(){
clearTimeout(carousel);
setTimeout(carousel, 6000);
})
答案 0 :(得分:4)
我认为您正在清除错误的变量超时。根据{{3}},它应该是超时的ID,因此:
t = setTimeout(carousel, 5000);
$(document).on('mousemove keyup keypress',function(){
clearTimeout(t);
t = setTimeout(carousel, 6000);
}
答案 1 :(得分:2)
此
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);
});
答案 2 :(得分:2)
问题出在这里
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
})