我有一个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让我清除它吗?
发布于 2013-07-14 08:11:13
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);
}
}发布于 2013-07-14 08:13:48
setTimeout()导致指定函数的一次执行。您想到的是setInterval(),它会一直执行,直到被取消。
在本例中,调用了clearTimeout(),但无论采用什么代码路径,代码都会继续设置另一个超时。
在调用func()之后尝试returning,以避免再次设置超时。
https://stackoverflow.com/questions/17635319
复制相似问题