Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 388
Tushar Raj Avatar asked Jun 22 '26 05:06

Tushar Raj


2 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.

like image 162
StPaulis Avatar answered Jun 23 '26 19:06

StPaulis


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().

like image 39
Willy Tjandra Avatar answered Jun 23 '26 20:06

Willy Tjandra