Clean breakdown of managing setInterval references with refs to avoid stale closures on pause/resume. One subtle edge case we ran into when building live global game-event countdowns (like our unofficial fan Fortnite Out of Time Event Countdown) is browser background-tab throttling: if you decrement seconds - 1 inside setInterval, switching tabs on mobile or desktop causes the displayed clock to drift behind wall-clock time within minutes.
Storing the absolute UTC target timestamp (targetMs) and recomputing Math.max(0, targetMs - Date.now()) on every tick—and pairing it with Intl.DateTimeFormat for automatic local timezone display—completely eliminates drift even when a user leaves the tab open for hours before an event starts.
linxi ye
Clean breakdown of managing
setIntervalreferences with refs to avoid stale closures on pause/resume. One subtle edge case we ran into when building live global game-event countdowns (like our unofficial fan Fortnite Out of Time Event Countdown) is browser background-tab throttling: if you decrementseconds - 1insidesetInterval, switching tabs on mobile or desktop causes the displayed clock to drift behind wall-clock time within minutes.Storing the absolute UTC target timestamp (
targetMs) and recomputingMath.max(0, targetMs - Date.now())on every tick—and pairing it withIntl.DateTimeFormatfor automatic local timezone display—completely eliminates drift even when a user leaves the tab open for hours before an event starts.