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