Spaces:
Running

WorkPilot-AI / web /src /lib /use-now.ts
Aynkhn's picture
Deploy WorkPilot demo (part 3)
03608f2 verified
Raw History Blame Contribute Delete
1.21 kB
"use client";
import { useSyncExternalStore } from "react";
// One shared clock per interval, so 50 inbox cards tick together without 50 timers.
interface Clock {
subscribe: (fn: () => void) => () => void;
get: () => number;
}
const clocks = new Map<number, Clock>();
function makeClock(ms: number): Clock {
let now = Date.now();
let timer: number | undefined;
const subs = new Set<() => void>();
return {
get: () => now,
subscribe: (fn) => {
subs.add(fn);
if (timer === undefined) {
now = Date.now();
timer = window.setInterval(() => {
now = Date.now();
for (const s of subs) s();
}, ms);
}
return () => {
subs.delete(fn);
if (!subs.size && timer !== undefined) {
window.clearInterval(timer);
timer = undefined;
}
};
},
};
}
function clock(ms: number): Clock {
let c = clocks.get(ms);
if (!c) {
c = makeClock(ms);
clocks.set(ms, c);
}
return c;
}
export function useNow(intervalMs = 1000): number {
const c = clock(intervalMs);
return useSyncExternalStore(c.subscribe, c.get, c.get);
}