clearInterval in React

Lucas picture Lucas · Aug 24, 2017 · Viewed 21.7k times · Source

I'm new at React and I was trying to create a simple stopwatch with a start and stop buttons. I'm banging my head against the wall to try to clearInterval with an onClick event on Stop button. I would declare a variable for the setInterval and then would clear it using the clearInterval. Unfortunately it is not working. Any tips? Thank you in advance.

import React, { Component } from 'react';

class App extends Component {
  constructor(props){
    super(props);
    this.state = {time:0}

    this.startHandler = this.startHandler.bind(this);
  }

  getSeconds(time){
    return `0${time%60}`.slice(-2);
  }

  getMinutes(time){
    return Math.floor(time/60);
  }

  startHandler() {
      setInterval(()=>{
      this.setState({time:this.state.time + 1});
    },1000)

  }

  stopHandler() {
    //HOW TO CLEAR INTERVAL HERE????
  }

  render () {
    return (
      <div>
        <h1>{this.getMinutes(this.state.time)}:{this.getSeconds(this.state.time)}</h1>
        <button onClick = {this.startHandler}>START</button>
        <button onClick = {this.stopHandler}>STOP</button>
        <button>RESET</button>
      </div>
    );
  }
}

export default App;

Answer

Dinesh Patil picture Dinesh Patil · Oct 27, 2017

you can add interval to your component's state and can clear it whenever you want.

componentDidMount(){
  let intervalId = setInterval(this.yourFunction, 1000)
  this.setState({ intervalId: intervalId })
}

componentWillUnmount(){
  clearInterval(this.state.intervalId)
}