Open History to see the last commit
1import { useSyncExternalStore } from "react";
2
3// Share wall-clock ticks so duration labels repaint in one frame.
4
5function currentSecond(): number {
6 return Math.floor(Date.now() / 1000) * 1000;
7}
8
9let nowSecond = currentSecond();
10let timerId: number | null = null;
11const listeners = new Set<() => void>();
12
13function scheduleTick(): void {
14 timerId = window.setTimeout(
15 () => {
16 nowSecond = currentSecond();
17 for (const listener of listeners) listener();
18 scheduleTick();
19 },
20 1000 - (Date.now() % 1000),
21 );
22}
23
24function subscribe(listener: () => void): () => void {
25 if (listeners.size === 0) scheduleTick();
26 listeners.add(listener);
27 return () => {
28 listeners.delete(listener);
29 if (listeners.size === 0 && timerId !== null) {
30 window.clearTimeout(timerId);
31 timerId = null;
32 }
33 };
34}
35
36function getSnapshot(): number {
37 if (timerId === null) nowSecond = currentSecond();
38 return nowSecond;
39}
40
41export function useNowSecond(): number {
42 return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
43}