I've a setInterval timer in useEffect and I want the timer to start from zero on page refresh. But it's not.
const [timer, setTimer] = useState(0)
useEffect(() => {
const timer = setInterval(() => {
const d = new Date(),
seconds = d.getMinutes() * 60 + d.getSeconds(),
totalTime = 60 * 6,
tL = totalTime - (seconds % totalTime),
r = `${parseInt(tL / 60, 10)}:${tL % 60}`;
setTimer(r);
}, 1000);
return () => clearInterval(timer);
}, []);
If you want a simple countdown, you can do something like this (i.e. derive your state from the number of seconds passed):
However, using
setInterval()to increment your timer is actually somewhat of a naive approach because it's not guaranteed to execute immediately after the specified time has passed (if the main thread is busy). The more robust approach is to derive the seconds passed from some start time value like so: