Javascript 在同一函数(NodeJs)中停止多个setInterval
我正在尝试取消多个计时器-以下是我的代码:Javascript 在同一函数(NodeJs)中停止多个setInterval,javascript,loops,setinterval,Javascript,Loops,Setinterval,我正在尝试取消多个计时器-以下是我的代码: timer1 = setInterval(func1,3000) stopper=999 count=5 function func1(){ console.log("called func1 ") if(count<=0){ //Count check, if zero , stop looping clearInterval(timer1) clearInterval(ti
timer1 = setInterval(func1,3000)
stopper=999
count=5
function func1(){
console.log("called func1 ")
if(count<=0){ //Count check, if zero , stop looping
clearInterval(timer1)
clearInterval(timer2)
}else{ //if count bigger than 0
timer2 = setInterval(func2,3000)
function func2(){
count=count-1
console.log("Called Func2 " + stopper)
stopper=count
}
}
}
timer1=setInterval(func13000)
止动块=999
计数=5
函数func1(){
log(“称为func1”)
如果(count发生这种情况的原因是每次调用func1时,都会向堆栈中添加一个新的setInterval
一种可能的解决方案是将timer2的setInterval替换为setTimeout
timer1 = setInterval(func1,3000)
stopper=999
count=5
function func1(){
console.log("called func1 ")
if(count<=0){ //Count check, if zero , stop looping
clearInterval(timer1)
clearTimeout(timer2)
}else{ //if count bigger than 0
timer2 = setTimeout(func2,3000)
function func2(){
count=count-1
console.log("Called Func2 " + stopper)
stopper=count
}
}
}
timer1=setInterval(func13000)
止动块=999
计数=5
函数func1(){
log(“称为func1”)
如果(count原因是当从func1
调用setInterval(func23000)
时,timer2
每次都被setInterval
调用的新id覆盖
您正在为func1
设置一个setInterval
,开始时,它在else
块中为func2
安排几个setInterval
调用。正在调用func1
5次,并且为每个func1
设置一个单独的setInterval
e> 打电话
现在有多个id
为func2
设置了多个间隔,每次发生这种情况时,timer2
都会被id的最新值覆盖
因此,当count
达到0
时,实际上取消了func2
的一个间隔id设置,其他间隔id设置仍继续运行
您可以维护一个数组,从setInterval
调用func2
中捕获ID,并在count
达到0:
(函数(){
常数计时器1=设置间隔(FUNC13000)
让塞子=999
让计数=5
常数timerIds=[];
函数func1(){
log(“称为func1”)
if(计数清除间隔(id));
}else{//如果计数大于0
timerIds.push(设置间隔(func23000));
函数func2(){
计数=计数-1
log(“调用Func2”+stopper)
停止=计数
}
}
}
})();
我真的需要设置间隔,因为我需要循环,但是你的第二个答案是正确的!谢谢
timer1 = setInterval(func1,3000)
stopper=999
count=5
function func1(){
console.log("called func1 ")
if(count<=0){ //Count check, if zero , stop looping
clearInterval(timer1)
clearInterval(timer2)
}else{ //if count bigger than 0
timer2 = setInterval(func2,3000)
function func2(){
count=count-1
console.log("Called Func2 " + stopper)
stopper=count
clearInterval(timer2)
}
}
}