如何正确重启Java超时?

时间:2019-04-18 18:48:49

标签: javascript

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

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

3 个答案:

答案 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
})