简体   繁体   中英

Decreasing counter has bizarre behaviour

I'm building a counter with setInterval who decreases the time every second, works for the first few seconds, then get stuck and increases and decreases at the same time.

In my case i start it 5:00 (m:ss) and after a few seconds blocks arround 4:49 and start increasing then decreasing...

not sure what is gooing on.

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>

You are capturing the timeLeft variable in a closure outside the interval function. So it gets captured once when start is pressed and remains the same value afterwards. Instead use the setState variant that accepts callback.

start = () => {
        console.log('starting')
        const interval = setInterval(() => {
             this.setState(state => { 
                  if (state.totalDuration > 0) 
                    return { totalDuration : state.totalDuration - 1000 }
                  else {
                    clearInterval(interval)
                    return {}
                  }
              })
        }, 1000)
    }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM