为什么这个 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
。
如果您希望变量在调用之间保持其值,则需要在函数外声明变量。
为什么 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
。
如果您希望变量在调用之间保持其值,则需要在函数外声明变量。