Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearInterval in React

Tags:

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; 
like image 317
Lucas Avatar asked Aug 24 '17 13:08

Lucas


People also ask

What is clearInterval in React?

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.

Why do we need clearInterval?

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.

What is JavaScript clearInterval?

The clearInterval() method clears a timer set with the setInterval() method.


1 Answers

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) } 
like image 122
Dinesh Patil Avatar answered Sep 27 '22 19:09

Dinesh Patil