如何在 Javascript 中正确重新启动超时



我有一个幻灯片轮播,我每隔 5 秒旋转一次。我有一个清除超时以停止旋转的功能。我正在尝试使用以下代码重新启动轮播。该行为有效,但不正确。它不是以 5 秒的间隔恢复,而是在幻灯片中快速闪烁。

t = setTimeout(carousel, 5000); 
var interval;
$(document).on('mousemove keyup keypress',function(){
    clearTimeout(carousel);
    setTimeout(carousel, 6000);
})

我认为您正在清除不正确变量的超时。根据文档,它应该是超时的id,因此:

t = setTimeout(carousel, 5000); 
$(document).on('mousemove keyup keypress',function(){
    clearTimeout(t);
    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
})

    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);
});

最新更新