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;
Clearing setInterval in React A function or block of code that is bound to an interval executes until it is stopped. To stop an interval, you can use the clearInterval() method. For example, the code below schedules a new interval when the React component mounts for the first time.
You'll need to use the clearInterval() method. It's meant to stop the timer set by using the setInterval JavaScript function. The setInterval() returns a variable called an interval ID.
The clearInterval() method clears a timer set with the setInterval() method.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With