Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useNowSecond.ts

46 lines1.2 KB

1import { useSyncExternalStore } from "react";
2​
3// One shared tick on wall-clock second boundaries: every live duration label
4// updates in the same frame instead of each repainting on its own phase.
5​
6function currentSecond(): number {
7 return Math.floor(Date.now() / 1000) * 1000;
8}
9​
10let nowSecond = currentSecond();
11let timerId: number | null = null;
12const listeners = new Set<() => void>();
13​
14function scheduleTick(): void {
15 timerId = window.setTimeout(
16 () => {
17 nowSecond = currentSecond();
18 for (const listener of listeners) listener();
19 scheduleTick();
20 },
21 1000 - (Date.now() % 1000),
22 );
24​
25function subscribe(listener: () => void): () => void {
26 if (listeners.size === 0) scheduleTick();
27 listeners.add(listener);
28 return () => {
29 listeners.delete(listener);
30 if (listeners.size === 0 && timerId !== null) {
31 window.clearTimeout(timerId);
32 timerId = null;
33 }
34 };
36​
37function getSnapshot(): number {
38 // While the timer runs the cached value is returned untouched, as
39 // useSyncExternalStore requires between change notifications.
40 if (timerId === null) nowSecond = currentSecond();
41 return nowSecond;
43​
44export function useNowSecond(): number {
45 return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);