如何结束`setInterval`?

huangapple go评论65阅读模式
英文:

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都会导致状态继续。感谢您的帮助 如何结束`setInterval`? 我正在等待时间结束。

英文:

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 如何结束`setInterval`?
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

huangapple
  • 本文由 发表于 2023年7月13日 19:19:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678775.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定