首页 > 解决方案 > 在同一个函数(NodeJs)中停止多个 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(timer2)
    }else{                  //if count bigger than 0
        timer2 = setInterval(func2,3000)
        function func2(){
            count=count-1
            console.log("Called Func2 " + stopper)
            stopper=count 
        }
    }
}

stopperhits时0,它停止写“Called Func1”,但它仍然一遍又一遍地写“Called Func2”,即使stopper-999- 我如何停止循环这个双 setInterval?

标签: javascriptloopssetinterval

解决方案


发生这种情况的原因是每次调用 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)
        }
    }
}

希望这可以帮助 :)


推荐阅读