Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stop setInterval and if not work in react native function

I have the code below:

contaTempo(){
  setInterval(() => this.setState({tempo: this.state.tempo+1}), 1000)
  if (this.state.tempo >= 5) {
    this.props.navigation.navigate('Sobre')
  }
}

The setInterval works correctly but the if doesn't work. Also, the timer neve stops. Any help?

like image 349
Italo Rodrigo Avatar asked Apr 23 '26 11:04

Italo Rodrigo


1 Answers

The if is running right away.

You want to place it inside the function passed to setInterval.

Also, you probably want to remove the timer as well, so call clearInterval() on the value returned by setInterval.

Furthermore, to prevent adding more than necessary to the this.state.tempo, move it to the else of the if statement.

Changed code would be like:

contaTempo(){
  let myInterval = setInterval(() => {
    if (this.state.tempo >= 5) {
      clearInterval(myInterval);
      this.props.navigation.navigate('Sobre')
    } else {
      this.setState({tempo: this.state.tempo+1});
    }
  }, 1000)
}
like image 102
acdcjunior Avatar answered Apr 26 '26 05:04

acdcjunior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!