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)
        }
    }
}