// Keeps a screen up to date without a live connection: runs `run` every `ms` // while the page is visible, pauses while it is in a background tab, and runs // at once when the tab comes back. There is no push channel (messages are // relayed through the network and fetched), so this is as live as it gets. /** How often an open screen checks for news, in milliseconds. */ export const FOREGROUND_MS = 8_000; /** * Calls `run` every `ms` while `alive()` is true and `doc` is visible. The first * call is the caller's job (do it before calling this); the next one happens * after `ms`. Runs never overlap. Stops for good once `alive()` is false. */ export function keepFresh(alive: () => boolean, run: () => Promise, ms = FOREGROUND_MS, doc: Document = document): void { let timer: ReturnType | undefined; let running = false; const stop = () => { clearTimeout(timer); doc.removeEventListener("visibilitychange", onVisible); }; const schedule = () => { clearTimeout(timer); timer = setTimeout(() => void fire(), ms); }; const fire = async () => { if (!alive()) return stop(); if (doc.hidden) return; // paused: becoming visible resumes it if (running) return schedule(); running = true; try { await run(); } catch { // A failed check is the caller's to show; the next one still happens. } finally { running = false; } if (!alive()) return stop(); schedule(); }; const onVisible = () => { if (!alive()) return stop(); if (doc.hidden) { clearTimeout(timer); return; } clearTimeout(timer); void fire(); }; doc.addEventListener("visibilitychange", onVisible); schedule(); }