我有一个超时,一旦使用清除就不会停止,我不确定为什么。
这是我的功能:
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);
}
}
关于javascript - 无法清除超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17635319/