我正在尝试取消多个计时器 - 这是我的代码:
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
}
}
}
当 stopper
命中 0
时,它会停止写入“Called Func1”,但它仍然一遍又一遍地写入“Called Func2”,即使 stopper
是 -999
- 如何停止循环此双 setInterval?
最佳答案
发生这种情况的原因是每次调用 func1 时都会将新的 setInterval 添加到堆栈中。
一个可能的解决方案是用 setTimeout 替换 timer2 的 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)
clearTimeout(timer2)
}else{ //if count bigger than 0
timer2 = setTimeout(func2,3000)
function func2(){
count=count-1
console.log("Called Func2 " + stopper)
stopper=count
}
}
}
第二种解决方案是在设置新定时器之前清除定时器 2。
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)
}
}
}
希望这有帮助:)
关于javascript - 在同一函数(NodeJs)中停止多个 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58997212/