繁体   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