javascript - 在同一个函数(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
}
}
}
当stopper
hits时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)
}
}
}
希望这可以帮助 :)
推荐阅读
- android - OpenCV for Android 通过 Visual Studio 到 Unity
- facebook - 如何正确包含 AdMob Facebook Audience Network 适配器?
- c++ - 为什么有些库使用非常量 char * 作为函数参数?
- javascript - 猫头鹰轮播上的图像在移动设备上被放大,我如何更改它以便它在移动设备上显示所有图像?
- javascript - 仅加载 safari 时动态内容移动到中间的页面
- mysql - 使用 SQL 同时加载多个时间序列
- r - R-Studio 过滤数据
- python - Django 列出匹配父级的类实例
- android - @react-native-firebase/admob 的基本用法给出:“TypeError: (0, _admob.default) 不是函数”。是否已弃用?或为什么不起作用?
- android - Kotlin Multiplatform 中共享抛出 NoSuchMethodError 的实际/预期乐趣