簡體   English   中英

為什么這個 clearInterval 不起作用?

[英]Why this clearInterval does not work?

為什么 clearInterval 不起作用? 當我第一次運行它時,它會輸出“Here”,然后它會創建第二個同時工作的計時器,依此類推。

     runTimer() {
     let _this = this
     let intervalID
     if (this.state.didTimerRun === false) {
        this.state.didTimerRun = true
        intervalID = setInterval(function() {
            if (_this.state.seconds !== 0) {
                _this.setState({
                    seconds: _this.state.seconds - 1,
                })
            } else if (_this.state.seconds === 0) {
                _this.setState({
                    seconds: 60,
                    workTime: _this.state.workTime - 1
                })
            }
        }, 1000)
    } else {
        console.log('Here')
        clearInterval(intervalID)
        _this.setState({
            workTime: 25,
            seconds: 0,
            didTimerRun: false
        })
    }

}

intervalID的范圍是runTimer函數。

每次調用runTimer ,都會使用不同的runTimer

如果您希望它在調用之間保持其值,則需要在函數外部聲明該變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM