Guillaume
Guillaume

Reputation: 547

Clearing setInterval() in ReactJS

I am creating an setInterval in my ReactJS app and I need to clear it later when the component unmounts. Thus, I can't achieve this goal with the following code that I use :

    var Timer = React.createClass ({

  getInitialState: function () {
    return ({
      timeLeft: "99:99:99"
    })
  },

  componentDidMount: function () {

    var compteur = setInterval( function () {
      var heure = new Date();
      var timeH = ((0 + this.props.endH - heure.getHours()) > 9) ? (0 + this.props.endH - heure.getHours()) : ("0" + (0 + this.props.endH - heure.getHours())) ;
      var timeM = ((0 + this.props.endM - heure.getMinutes()) > 9) ? (0 + this.props.endM - heure.getMinutes()) : ("0" + (0 + this.props.endM - heure.getMinutes())) ;
      var timeS = ((0 + this.props.endS - heure.getSeconds()) > 9) ? (0 + this.props.endS - heure.getSeconds()) : ("0" + (0 + this.props.endS - heure.getSeconds())) ;

      this.setState({
        timeH: timeH,
        timeM: timeM,
        timeS: timeS
      });

      this.setState ({
        timeLeft: this.state.timeH + ":" + this.state.timeM + ":" + this.state.timeS
       })

    }.bind(this), 900);

    compteur;

  },

  componentWillUnmount: function () {
    console.log("Unmounting Timer...");
    clearInterval(this.compteur);
    this.compteur = false;
  },

  render: function() {
    return (
      <div className="time-count">{this.state.timeLeft}</div>
    )
  }

});

The thing is, when I try to clear the interval right after setting it via clearInterval(compteur), it works. But it doesn't when I later try to do it with clearInterval(this.compteur).

Thanks !

Upvotes: 1

Views: 1195

Answers (1)

luiscrjr
luiscrjr

Reputation: 7268

When you're declaring compteur like this, you're telling this is a normal variable scopped into componentDidMount function.

Just replace

var compteur = setInterval( function () {

with

this.compteus = setInterval( function () {

And you'll be able to access this.compteur from componentWillUnmount function.

Working demo: https://jsfiddle.net/mrlew/bfexkpkx/

Upvotes: 1

Related Questions