I'm working on React pomodoro clock and I got stuck on joining if/else with setTimeout(). Here is my code:
React.useEffect(() => {
if(props.isOn === true) {
if(props.timeLeft <= 0) {
setTimeout(function() {
if(props.activeClockType === 'Session') {
props.handleClockType('Break');
props.handleTimeLeft(props.breakLength * 60);
} else {
props.handleClockType('Session');
props.handleTimeLeft(props.sessionLength * 60);
}
}, 1000);
}
const id = setInterval(count, 1000);
return () => clearInterval(id);
}
});
When the clock goes to 00:00 it's stopping for 1sec and then showing Break and timer sets to breakLength. Great, but after 1sec it's not counting down but changing back to Session and counting sessionLength.
When I delete setTimeout (commented in CodePen) it works good but it's not stopping at 00:00 for 1sec but immediately changes on Break what looks ugly.
How to make it stop on 00:00 for 1 second before counting other activeClockType?
I've spent whole evening on looking for any clue but still I don't have any idea what is wrong. I tried to put setTimeout in every possible combination with if but effect is always the same. From this topic I suspect that I should probably use clearTimeout but also tried it in any combination and got nothing.
Or maybe I should try another possibility to run countdown than useEffect()? Earlier I made working timer in class component (commented in CodePen) with componentWillReceiveProps but it's deprecated and my attempts to change it on other functions gave nothing. I don't fully understand this Effect Hook but it was the only way I found that is counting well. And it's shorter than class component.
Here is my full code on CodePen
Thank you in advance.