Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Can';清除超时_Javascript - Fatal编程技术网

Javascript Can';清除超时

Javascript Can';清除超时,javascript,Javascript,我有一个超时,它不会停止一旦清除是用在它,我不知道为什么 这是我的职责: 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)

我有一个超时,它不会停止一旦清除是用在它,我不知道为什么

这是我的职责:

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);
}
函数升级\u条(结束、开始、条、timerId、func){
var per=((new Date().getTime()/1000)-start)/(end-start)*100;
如果(per>100)per=100;
if(per
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);
    }
}
函数升级\u条(结束、开始、条、函数){
var per=((new Date().getTime()/1000)-start)/(end-start)*100;
如果(per>100)per=100;
如果(per
setTimeout()
导致指定函数的一次执行。您考虑的是
setInterval()
,它一直执行到取消为止

在您的例子中,调用了
clearTimeout()
,但无论采用何种代码路径,代码都会继续设置另一个超时


调用
func()后尝试
return
ing
避免再次设置超时。

啊,所以我把它和SetInterval混淆了。好吧,一个简单的
返回false
应该结束它,而不是清除它?还有为什么clearTimeOut会存在,它会有什么用。@Dave我看到clearTimeOut使用的一个地方是在自动完成中。当按下一个键时,你开始计时t表示500毫秒,但如果用户键入另一个字符,则取消它。这样,在500毫秒内没有键入任何字符之前,它实际上不会执行。@Dave我更新了我的答案来解释它。基本上,可以在到达时间之前调用clearTimeout来取消它。啊,我认为他们应该将它命名为“AbortTimeOut”之类的名称避免与SetInterval的混淆version@Dave是的,abort是对其功能的更好描述。那么clearTimeOut()在JS中的实际用途是什么呢