0

I am working in react. I want to clear my interval on componentWillUnmount

The interval is set as this

setInterval( () => this.baz(), 1000 );

Following this answer here Referencing "this" inside setInterval/setTimeout within object prototype methods

How do I clear that. I am sorry if this is a basic question

user3808307
  • 2,270
  • 9
  • 45
  • 99

2 Answers2

4

Save a reference to the intervalID on the component (this.intervalID), and clear it in componentWillUnmount:

class Demo extends React.Component {
  componentDidMount() {
    this.intervalID = setInterval( () => this.baz(), 1000 );
  }

  componentWillUnmount() {
    clearInterval(this.intervalID);
  }

  render() {
    //...
  }
}
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
2

setInterval returns an ID when you call it. You simply need to save that and pass it to clearInterval(). You can very easily save that in your state:

this.setState({ intervalId: setInterval(() => this.baz(), 1000) });

And then in componentWillUnmount():

clearInterval(this.state.intervalId);
samanime
  • 25,408
  • 15
  • 90
  • 139