mastermind/web/app/multiplayer/useTicker.js

38 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2026-11-21 22:37:05 +03:00
'use client';
import { useEffect, useRef } from 'react';
/**
* Calls `callback` every `intervalMs`. The timer runs in a Web Worker because browsers
* heavily throttle timers of background tabs; the poll doubles as the server heartbeat,
* so a throttled tab would otherwise be treated as "left".
*/
export default function useTicker(callback, intervalMs, enabled = true) {
const saved = useRef(callback);
useEffect(() => {
saved.current = callback;
}, [callback]);
useEffect(() => {
if (!enabled) return;
const tick = () => saved.current();
tick();
let worker = null;
let url = null;
let timer = null;
try {
const src = `setInterval(() => postMessage(0), ${intervalMs});`;
url = URL.createObjectURL(new Blob([src], { type: 'text/javascript' }));
worker = new Worker(url);
worker.onmessage = tick;
} catch {
timer = setInterval(tick, intervalMs);
}
return () => {
if (worker) worker.terminate();
if (url) URL.revokeObjectURL(url);
if (timer) clearInterval(timer);
};
}, [intervalMs, enabled]);
}