So, we have this simple React component that receives an integer from the father component. When the button is clicked, we display the integer on the screen and the countdown begins.
The question is how can I stop the countdown. While reading other SO posts, I found about clearInterval(), but it seems I am missing something here.
Any help would be greatly appreciated. Bonus appreciation points will be awarded if someone is kind enough to explain to me why the sample code is not working as expected.
import React from "react";
export default class TestInterval extends React.Component {
constructor(props) {
super(props);
this.state = {
countDown: this.props.countDown, // An integer from father component
}
}
timer = () => {
setInterval(() => {
if (this.state.countDown === 0) {
this.stopCountDown();
}
this.setState( prevState => ({
countDown: prevState.countDown - 1,
}));
}, 1000)
}
startCountDown = () => {
this.timer();
}
stopCountDown = () => {
clearInterval(this.timer); // Not working
}
render () {
return (
<div>
<button onClick={this.startCountDown}>
Start Countdown
</button>
<p>{this.state.countDown}</p>
</div>
);
}
}