簡體   English   中英

無法清除TimeOut

[英]Can't clearTimeOut

我有一個TimeOut,一旦使用了clear就不會停止,我不確定為什么。

這是我的功能:

function upgrade_bar(end, start, bar, timerId, func) {      

    var per = ( (new Date().getTime() / 1000) - start ) / ( end - start ) * 100;

    if(per>100)per=100;
    if(per<0)per = 0;

    if(per == 0) {
        bar.style.width = per + "%";
    } else if(per == 100) {
        clearTimeout(timerId); //this does not stop it
        if(func !== false){
            func(); //this does call at 100%
        }
    } else{
        bar.style.width = per+ "%";
    }
    console.log('still going');
    timerId = setTimeout(function() { upgrade_bar(end, start, bar, timerId, func) } , 17);
}

我誤解了什么? timerId是否持有暫停的ID以供我清除?

setTimeout()只計划執行一次該函數。

clearTimeout()可以用來達到時間之前停止即將到來的超時 - 但是一旦達到超時並且已經調用了該函數,清除超時什么都不做 - 它無論如何都不會再次運行。

這里的問題是,無論你的函數發生了什么,你都可以通過再次調用setTimeout來結束 - 安排它再次運行。


一個可能的解決方案是重寫您的函數,如下所示:

function upgrade_bar(end, start, bar, func){       
    var per = ( (new Date().getTime() / 1000) - start ) / ( end - start ) * 100;
    if (per>100) per=100;
    if (per<0) per = 0;

    bar.style.width = per + "%";

    if (per == 100) {
        if (func !== false) {
            func(); //this does call at 100%
        }
    } else {
        console.log('still going');
        setTimeout(function() { upgrade_bar(end, start, bar, func) } , 17);
    }
}

setTimeout()導致一次執行指定的函數。 您正在考慮setInterval() ,它會一直執行,直到被取消。

在您的情況下,調用clearTimeout() ,但無論采用何種代碼路徑,代碼都會繼續設置另一個超時。

在調用func()后嘗試return ,以避免再次設置超時。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM