[英]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.