Italo Rodrigo
Italo Rodrigo

Reputation: 1785

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?

Upvotes: 10

Views: 15939

Answers (1)

acdcjunior
acdcjunior

Reputation: 135762

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)
}

Upvotes: 14

Related Questions