我正在使用 setInterval 构建一个计数器,它每秒减少时间,在开始的几秒钟内工作,然后卡住并同时增加和减少。
在我的例子中,我从 5:00 (m:ss) 开始,几秒钟后大约 4:49 开始增加然后减少......
不确定发生了什么。
start = () => {
console.log('starting')
let timeLeft = this.state.totalDuration
setInterval(() => {
if (timeLeft > 0) {
timeLeft = (timeLeft - 1000)
this.setState({ totalDuration: timeLeft })
}
}, 1000)
}
render() {
return (
<View style={styles.container}>
<Timer interval={this.state.totalDuration}></Timer>
<ButtonsRow>
<RoundButton title='Reset' color='white' background='grey'></RoundButton>
<RoundButton onPress={this.start()} title='Start' color='white' background='red'></RoundButton>
</ButtonsRow>
</View>
最佳答案
您正在间隔函数外的闭包中捕获 timeLeft
变量。因此,当按下开始时它会被捕获一次,之后保持相同的值。而是使用接受回调的 setState
变体。
start = () => {
console.log('starting')
const interval = setInterval(() => {
this.setState(state => {
if (state.totalDuration > 0)
return { totalDuration : state.totalDuration - 1000 }
else {
clearInterval(interval)
return {}
}
})
}, 1000)
}
关于javascript - 递减计数器有奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56620146/