Hello,
I am working on Pomodoro Clock project and having trouble with setInterval() in React function.
The below decrementDisplayTimer() decrements the time on the main display every second and it works if I set this function on “Start/Stop” button and press it manually.
decrementDisplayTimer(){
console.log(this.state.timeLeft)
var minutes = Math.floor(this.state.timeLeft / 60);
var seconds = this.state.timeLeft % 60;
this.state.timeLeft--;
minutes = Math.floor(this.state.timeLeft / 60);
seconds = this.state.timeLeft % 60;
this.setState({
timeLeft:this.state.timeLeft,
timerDisplay: minutes + ":" + seconds,
});
}
However, when I set this function in countDownHandlar() as below, the count down doesn’t start from the main display count (timeLeft:1500). I checked the console.log (this.state.timeLeft) to see what’s going on and it seems like it always start counting down from “3” and I can’t figure out where the number is coming from.
countDownHandlar(){
let startCountdown = setInterval(()=>{
this.decrementDisplayTimer();
if(this.state.timeLeft===0){
console.log("done!")
clearInterval(startCountdown)
}
}, 1000)
this.setState({
timeLeft: startCountdown
})
}
It would be great if someone could help me on this.
Here is my codepen: https://codepen.io/eriko87/pen/PrdeqN
Thanks!