I want to make a countdown timer with start, stop, resume and reset buttons. However, I could not figure out why my code does not work. I am guessing that the issue lies in the part on timer, setInterval and clearInterval.
I have attached snippets of my code below.
Help would be greatly appreciated, thanks!
function Countdown() {
const [ timerRunning, setTimerRunning ] = useState(false);
const [ startTime, setStartTime ] = useState(0);
const [ totalTime, setTotalTime ] = useState(0);
var timer;
const startTimer = () => {
setTimerRunning(true);
setStartTime(totalTime);
setTotalTime(totalTime);
timer = setInterval(() => {
const remainingTime = totalTime - 1000;
if (remainingTime >= 0) {
setTotalTime(remainingTime);
} else {
clearInterval(timer);
setTimerRunning(false);
setStartTime(0);
setTotalTime(0);
}
}, 1000);
};
const stopTimer = () => {
clearInterval(timer);
setTimerRunning(false);
};
useState doesn't change value immediately. So it's value is not actually changing. To avoid this use UseEffect hook.
useEffect(() => {
let intervalid
if (timerRunning){
intervalid = setInterval(() => {
const remainingTime = totalTime - 1000;
if (remainingTime >= 0) {
setTotalTime(remainingTime);
} else {
clearInterval(intervalid);
setTimerRunning(false);
setStartTime(0);
setTotalTime(0);
}
}, 1000);
}
return () => {
clearInterval(intervalid)
}
}, [timerRunning,totalTime])