Why does clearInterval not work? When I run it the first time it works, then it outputs "Here", then it creates the second timer that works simultaneously and so on.
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
is scoped to the runTimer
function.
Each time you call runTimer
, you use a different runTimer
.
You need to declare the variable outside the function if you want it to maintain its values between invocations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.