import { useEffect, useRef } from "react"; /** * Calls `fn` now, then every `ms` while the tab is visible, again when the tab shows, and whenever the * optional window event fires. The latest `fn` is used without restarting the timer. */ // ponytail: polling (30 s list, 10 s thread); server-sent events if the delay ever matters. export function usePolling(fn: () => void, ms: number, refreshEvent?: string, enabled = true) { const latest = useRef(fn); useEffect(() => { latest.current = fn; }); useEffect(() => { if (!enabled) return; const run = () => { if (!document.hidden) latest.current(); }; run(); const id = window.setInterval(run, ms); document.addEventListener("visibilitychange", run); if (refreshEvent) window.addEventListener(refreshEvent, run); return () => { window.clearInterval(id); document.removeEventListener("visibilitychange", run); if (refreshEvent) window.removeEventListener(refreshEvent, run); }; }, [ms, refreshEvent, enabled]); }