In my application I want to display a timer which can be started and stopped by the user. For this I created a timer state: const [timer, setTimer] = useState({"minutes" : 0, "seconds" : 0})and use a useEffect hook to increment the values periodically.
If I'm using:
useEffect(() => {
const displayTimer = setTimeout(() => {
if(timer.seconds < 59) {
setTimer({"minutes": timer.minutes, "seconds" : timer.seconds + 1})
}
else {
setTimer({"minutes": timer.minutes + 1, "seconds" : 0})
}
}, 1000);
return () => clearTimeout(displayTimer);
});
everything works fine. The timer runs until infinity. But after adding the if statement, to stop the timer, nothing happens anymore. I can't start the timer.
Heres the code:
useEffect(() => {
const displayTimer = setTimeout(() => {
if(active) {
if(timer.seconds < 59) {
setTimer({"minutes": timer.minutes, "seconds" : timer.seconds + 1})
}
else {
setTimer({"minutes": timer.minutes + 1, "seconds" : 0})
}
}
}, 1000);
return () => clearTimeout(displayTimer);
});
The active var is a useState hook which is toggled by a button.
With console.log I found out, the useEffect isn't called anymore after adding the if. But why? Can anyone help me to get my timer working?