javascript - 在同一函数(NodeJs)中停止多个 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(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/

相关文章:

javascript - 非同步启动 Javascript 间隔并在运行 3 次后停止

java - 具有相同性能的内循环(易碎)替代方案

javascript - rails 、jQuery : onClick event not attaching?

search - php分页和搜索

javascript - setInterval 似乎不起作用?

javascript - 每 10 秒使用 querySelector 更改背景图像不起作用

reactjs - 如何解决警告 "Warning: Can' t perform a React state update on an unmounted component."from setInterval function?

javascript - 为什么不能使用原型(prototype)将属性绑定(bind)到对象?

javascript - JS 应该选择第二个选项,我们使用了 selected ="selected"

javascript - 如何居中对齐 TemplateField 的标题文本?