forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

create-live-poll.ts54 lines, 1.8 KiBHistoryRawDownload
1import { onCleanup } from "solid-js";
2
3/**
4 * Visibility-aware polling primitive. Call inside a component/owner scope.
5 *
6 * Why this exists: a plain `setInterval(refetch, ms)` keeps firing in hidden
7 * tabs (wasted GETs) and never catches up when the user returns — so state
8 * changed by *another* actor (e.g. a teacher approving a student's appointment)
9 * shows up to one full interval stale on a parked tab. This runs the interval
10 * only while the tab is visible, and refetches immediately when the tab becomes
11 * visible or the window regains focus, so tab-back is instant-fresh.
12 *
13 * Pair with `resource.latest` reads (see AGENTS.md #6): a refetch never
14 * re-suspends, so the poll can't blank a shell that sits beside <Outlet>.
15 *
16 * @param refetch called on each visible tick and on visibility/focus wake.
17 * @param intervalMs poll period while visible (default 30s).
18 */
19export function createLivePoll(refetch: () => unknown, intervalMs = 30_000): void {
20 let timer: ReturnType<typeof setInterval> | undefined;
21 let lastRun = 0;
22 const run = () => {
23 lastRun = Date.now();
24 void refetch();
25 };
26 const start = () => {
27 if (!timer) timer = setInterval(run, intervalMs);
28 };
29 const stop = () => {
30 if (timer) {
31 clearInterval(timer);
32 timer = undefined;
33 }
34 };
35 // visibilitychange (tab switch) and window focus can both fire on tab-back;
36 // the 1s guard collapses that into a single refetch.
37 const wake = () => {
38 if (document.hidden) {
39 stop();
40 return;
41 }
42 if (Date.now() - lastRun > 1_000) run();
43 start();
44 };
45
46 if (!document.hidden) start();
47 document.addEventListener("visibilitychange", wake);
48 window.addEventListener("focus", wake);
49 onCleanup(() => {
50 stop();
51 document.removeEventListener("visibilitychange", wake);
52 window.removeEventListener("focus", wake);
53 });
54}