2

I'm working on an application and I have a timer with the current date, hour, minutes and seconds displayed. It is incremented every second. What I want to do is to stop the timer on a button click, but I'm not sure why the clearInterval() function doesn't work. My code is:

class Timer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
           timer: "",
        };
    }

    componentDidMount() {
        //current time
        setInterval(() => {
            this.setState({
                currentTime : new Date().toLocaleString()
            })
        }, 1000)
    }


   stopTimer = () => {
        clearInterval(this.state.currentTime)
  }

   render() {
        return (
                <div>
                    <h4>Current time: {this.state.currentTime}</h4>
                    <Button onClick={this.stopTimer}>Stop timer</Button>
                </div>
              )
   }

}
user14681827
  • 143
  • 1
  • 10
  • 1
    Does this answer your question? [setInterval in a React app](https://stackoverflow.com/questions/36299174/setinterval-in-a-react-app) – Emile Bergeron Dec 15 '20 at 20:22

2 Answers2

6

setInterval() result is the intervalID and you should use this for clearInterval().

this.state = {
  ...
  intervalId: ""
};

...

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

...

clearInterval(this.state.intervalId);
wangdev87
  • 8,611
  • 3
  • 8
  • 31
2

You are using the clearInterval on wrong variable . You should do this.

I'm working on an application and I have a timer with the current date, hour, minutes and seconds displayed. It is incremented every second. What I want to do is to stop the timer on a button click, but I'm not sure why the clearInterval() function doesn't work. My code is:

class Timer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
           timer: "",
           intervalId: ""
        };
    }

    componentDidMount() {
        //current time
       const intervalId =  setInterval(() => {
            this.setState({
                currentTime : new Date().toLocaleString()
            })
        }, 1000); 

     this.setState({intervalId})
    }


   stopTimer = () => {
     if (this.state.intervalId) {
       clearInterval(this.state.intervelId)
     }
  }

   render() {
        return (
                <div>
                    <h4>Current time: {this.state.currentTime}</h4>
                    <Button onClick={this.stopTimer}>Stop timer</Button>
                </div>
              )
   }

}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Zurez
  • 191
  • 2
  • 10