Z.T
Z.T

Reputation: 13

react-native clearInterval doesnt work in android

this is my code, everything is good except stopTimer method which includes clearInterval:

componentDidMount() {
  this.insertArray();
  that = this;

  this.setState({
    interval: setInterval(function() {
      let elapsed_time=(Math.floor(Date.now() / 1000)) - that.state.data;
      that.setState({
        elapsed: that.secondsToHms(elapsed_time)
      });
    }, 1000)
  });     
}

secondsToHms(d){
  d = Number(d);
  var h = Math.floor(d/3600);
  var m = Math.floor(d%3600/60);
  var s = Math.floor(d%3600%60);

  return ('0' + h).slice(-2) + ":" + ('0' + m).slice(-2) + ":"+ ('0' + s).slice(-2);
}

stopTimer(){
  clearInterval(this.state.interval);
}

thats how I call stopTimer method:

 <TouchableOpacity onPress={()=>this.stopTimer()>  
 <Text>stopTimer</Text>
   </TouchableOpacity>

Upvotes: 0

Views: 375

Answers (1)

Benoit
Benoit

Reputation: 1921

State is not the right place to store such a reference. It does not represent the state of your view.

Since there is no quick clean way to do this, keep the reference of the timeout in this, this being your component. It will work on Android.

this.interval = setInterval(function() {})

Also, do not forget to clear when componentWillUnmount is triggered.

Upvotes: 1

Related Questions