Files
allmende/web/src/fresh.ts
T
nilsandClaude Sonnet 5.5 dc690a72c9 Poll every 8 s while visible, pause in background tabs
Conversations and the owner screen refreshed every 20 s and 30 s. A shared
keepFresh helper now checks every 8 s while the tab is visible, pauses when
it is hidden, catches up at once when it returns, never overlaps runs, and
stops when the screen is gone or the owner token is. The latter also stops
the sign-in form being redrawn under someone typing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 20:58:45 +01:00

54 lines
1.7 KiB
TypeScript

// 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<void>, ms = FOREGROUND_MS, doc: Document = document): void {
let timer: ReturnType<typeof setTimeout> | 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();
}