Stop function is not working as expected. Need Help. React

Viewed 151

So I'm new to React and I have made a timer that increases after clicking on Start. Similarly, I made a stop button to stop the timer and set the variable to 0. But what's happening is it starts again from 0.

Help would be appreciated. Thanks in Advance.

import React from 'react';
class Timer extends React.Component {
    constructor() {
    super();
    this.state = {
            secondsElapsed: 0
        };
    }
    start = () => {
        this.setState({
            secondsElapsed: this.state.secondsElapsed + 1
        });
    }
    stop = () => {
        this.setState({
            secondsElapsed: 0
        });
    }

    handleClick = (e) => {
        this.interval = setInterval(this.start, 1000);
    }

    render() {
        return ( <React.Fragment><br/>
        <ul>
                    <li><span onClick = {this.handleClick}> Start Timer <br/><br/></span></li>
                    <li><span onClick = {this.stop}> Stop Timer </span></li>
        </ul>
                    
                    <Resultant new = {this.state.secondsElapsed}/> 
                </React.Fragment>);
            }
}
class Resultant extends React.Component {
    render() {
            return ( <div>
                        <h3> Seconds Elapsed: {this.props.new} </h3> 
                    </div>);
                }
}
export default Timer;
4 Answers

You have to clear the interval to stop the function from running repeatedly:

stop = () => {
        clearInterval(this.interval);
        this.setState({
            secondsElapsed: 0
        });
    }

For more details about timing events in JavaScript here.

In your stop(), you are only resetting the secondElapsed state back to 0. You also need to stop the interval from updating the state again.

You can try adding clearInterval(this.interval) in the stop().

Change your stop function to this:

stop = () => {
    this.setState({
        secondsElapsed: 0
    });
    clearInterval(this.interval); // You should clear the interval to stop it from incrementing seconds when "stop" is pressed
}

Problem

You are using setInterval by assigning it to a value named interval by this.interval = setInterval() so it starts doing that each second but later after stopping it still uses it because you didn't stop interval so it is making it in the "background".

Solution

You just need to add line with clearing interval in the beginning of your stop function like:

  stop = () => {
       clearInterval(this.interval)
       // rest of code
   }

so it will stop running that in the background even if you click on the stop button.

Related