英文:
How to end setinterval?
问题
我有一个问题涉及到时间间隔。当我声明一个函数并在其中使用setInterval
,如果我使用clearInterval
来清除它,它仍然会继续执行。以下是代码:
if (score == 1) {
leftBlinkTimer(0)
} else if (score == 0) {
leftBlinkTimer(1)
}
function leftBlinkTimer(state) {
let leftBlin = 0;
var timer;
if (state == 0) {
timer = setInterval(() => {
if (leftBlin == 0) {
const newData = {
stateLeftBlinker: 'rgba(255, 255, 255, 1)'
}
vm.changeMicro(newData)
leftBlin = 1;
} else if (leftBlin == 1) {
const newData = {
stateLeftBlinker: '#47EC5B'
}
vm.changeMicro(newData)
leftBlin = 0;
}
}, 600)
} else if (state == 1 || state == '1') {
clearInterval(timer)
}
}
我尝试在定时器内检查状态并清除,但它似乎不起作用。无论是0还是1都会导致状态继续。感谢您的帮助 我正在等待时间结束。
英文:
I have problem is interval. When i declare function she have setinterval and if i clearinterval she continues to be executed. Code:
if (score == 1) {
leftBlinkTimer(0)
} else if (score == 0) {
leftBlinkTimer(1)
}
function leftBlinkTimer (state) {
let leftBlin = 0;
var timer;
if (state == 0) {
timer = setInterval(() => {
if (leftBlin == 0) {
const newData = {
stateLeftBlinker: 'rgba(255, 255, 255, 1)'
}
vm.changeMicro(newData)
leftBlin = 1;
} else if (leftBlin == 1) {
const newData = {
stateLeftBlinker: '#47EC5B'
}
vm.changeMicro(newData)
leftBlin = 0;
}
},600)
} else if (state == 1 || state == '1') {
clearInterval(timer)
}
I try check state in timer and clear, and it's not working. Both 0 and 1 come to state.Thanks for help
I'm waiting for the time to end
答案1
得分: 2
你面临的问题与leftBlinkTimer
函数内部的timer
变量的作用域有关。timer
变量在函数的作用域内声明,因此当你调用clearInterval(timer)
时,它不会引用之前调用leftBlinkTimer
时创建的相同timer
。
将其声明在外部会有所帮助。
英文:
The issue you're facing is related to the scoping of the timer
variable inside the leftBlinkTimer
function. The timer
variable is declared inside the function's scope, so when you call clearInterval(timer)
, it won't refer to the same timer
that was created in the previous call to leftBlinkTimer
.
declaring it outside would help
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论