How to use setInterval function with ReactJs – ES6

Some time you may go through some issues when using "setInterval" function. Let me explain and make sure you and I go through the same problem. I thought of writing this article because lots of reactjs developers  out there faced this problem and many were asked how to use "setInterval" function.

If you are using ES6 syntax for Reactjs web application development, when using "setInterval" you can not use class properties inside the "setInterval". It's because incorrect use of those functions inside the ES6 class. Due to that you can't clear "setInterval" when component unmounted. You have to bind those ready made JavaScript functions with ES6 class. I will explain a way of doing that. There are lots of ways that you can achieve this. Remember this not the only way of doing this.

componentDidMount() {
  if(this.props.autoPlay) {
    this.interval = setInterval(() => {
      //autoPlay some for specific period of times or
      // Do some stuff you want
    }, 3000);
  }
}

Make sure to clear interval before unmounting the component. Because if "setInterval" function called and during that time interval react component get unmounted after end of the interval it will create an error. This is how you clear interval when reactjs component get unmounted.

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

Add a Comment

Your email address will not be published.