为什么clearTimeout清除不了setTimeout

2025-12-05 15:50:31
推荐回答(2个)
回答1:

你没有在clearTimeout后return函数的结果,导致代码继续运行。


var t=3,timer;
function sleep(){
if(t<=0){
clearTimeout(timer);
alert("over");
//一定要return,不然下面有添加了新的定时器
return;
}
alert("hello");
t--;
timer = setTimeout("sleep()", 1000);
}
sleep();

回答2:

timer在js里面估计是关键字之类的,改成timer1或者其他的就行。别听那个赞多的,误人子弟