简体   繁体   English

无法清除TimeOut

[英]Can't clearTimeOut

I have a TimeOut which doesn't stop once clear is used on it and I am unsure why. 我有一个TimeOut,一旦使用了clear就不会停止,我不确定为什么。

This is my function: 这是我的功能:

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

What have i misunderstood about this? 我误解了什么? Doesn't timerId hold the Id of the timeout for me to clear it? timerId是否持有暂停的ID以供我清除?

setTimeout() just schedules one more execution of the function. setTimeout()只计划执行一次该函数。

clearTimeout() can be used to stop an upcoming timeout before the time is reached - but once the timeout is reached and the function has been called, clearing the timeout does nothing - it wasn't going to run again anyways. clearTimeout()可以用来达到时间之前停止即将到来的超时 - 但是一旦达到超时并且已经调用了该函数,清除超时什么都不做 - 它无论如何都不会再次运行。

The problem here is that regardless of what happens in your function, you end by calling setTimeout again - scheduling it to run again. 这里的问题是,无论你的函数发生了什么,你都可以通过再次调用setTimeout来结束 - 安排它再次运行。


A possible solution is to rewrite your function like this: 一个可能的解决方案是重写您的函数,如下所示:

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() causes one execution of the specified function. setTimeout()导致一次执行指定的函数。 You're thinking of setInterval() , which executes until canceled. 您正在考虑setInterval() ,它会一直执行,直到被取消。

In your case, clearTimeout() is called, but the code continues on to set another timeout, no matter what code path is taken. 在您的情况下,调用clearTimeout() ,但无论采用何种代码路径,代码都会继续设置另一个超时。

Try return ing after calling func() to avoid setting the timeout again. 在调用func()后尝试return ,以避免再次设置超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM