I’m wondering the best way to make a simple minute/second countdown timer to next refresh. This component’s prop get updated every 5 minutes and counts down until the next refresh per second. This seems to get out of sync pretty quickly. Any thoughts?
I’m not sure if timeRemaining < 0
makes sense — if we subtract 1000 from 1100 we would have 100 (how do I account for that?) I’m hoping there’s a better way. Should I convert this back to seconds?
Thanks for any feedback.
...
const CountdownToNextRefresh = ({milliToNextRounded5Min}) => {
const [, setCount] = useState(0);
const [timeRemaining, setTimeRemaining] = useState(milliToNextRounded5Min);
useEffect(() => {
const oneSecond = 1000;
const interval = setInterval(() => {
setCount((prevCount) => prevCount + 1);
setTimeRemaining(timeRemaining < 0 ? milliToNextRounded5Min : timeRemaining - oneSecond);
}, oneSecond);
return () => clearInterval(interval);
}, [timeRemaining, milliToNextRounded5Min]);
function msToTime(milliseconds) {
// Get hours from milliseconds.
const hoursFromMilli = milliseconds / (1000*60*60);
const absoluteHours = Math.floor(hoursFromMilli);
const h = absoluteHours > 9 ? absoluteHours : `0${absoluteHours}`;
// Get remainder from hours and convert to minutes.
const minutesfromHours = (hoursFromMilli - absoluteHours) * 60;
const absoluteMinutes = Math.floor(minutesfromHours);
const m = absoluteMinutes > 9 ? absoluteMinutes : `0${absoluteMinutes}`;
// Get remainder from minutes and convert to seconds.
const seconds = (minutesfromHours - absoluteMinutes) * 60;
const absoluteSeconds = Math.floor(seconds);
const s = absoluteSeconds > 9 ? absoluteSeconds : `0${absoluteSeconds}`;
return h === "00" ? `${m}:${s}` : `${h}:${m}:${s}`;
}
return (<div>{msToTime(timeRemaining)}</div>)
}