Open History to see the last commit
1import { useSyncExternalStore } from "react";
2
3function currentMinute(): string {
4 return new Date().toISOString().slice(0, 16);
5}
6
7let nowMinute = currentMinute();
8let timerId: number | null = null;
9let timerIsInterval = false;
10const listeners = new Set<() => void>();
11
12function tick(): void {
13 const next = currentMinute();
14 if (next !== nowMinute) {
15 nowMinute = next;
16 for (const listener of listeners) listener();
17 }
18}
19
20function startTimer(): void {
21 timerIsInterval = false;
22 timerId = window.setTimeout(
23 () => {
24 tick();
25 timerIsInterval = true;
26 timerId = window.setInterval(tick, 60_000);
27 },
28 60_000 - (Date.now() % 60_000),
29 );
30}
31
32function subscribe(listener: () => void): () => void {
33 if (listeners.size === 0) {
34 startTimer();
35 }
36 listeners.add(listener);
37 return () => {
38 listeners.delete(listener);
39 if (listeners.size === 0 && timerId !== null) {
40 if (timerIsInterval) window.clearInterval(timerId);
41 else window.clearTimeout(timerId);
42 timerId = null;
43 }
44 };
45}
46
47function getSnapshot(): string {
48 // While the timer runs the cached value is returned untouched, as
49 // useSyncExternalStore requires between change notifications.
50 if (timerId === null) {
51 nowMinute = currentMinute();
52 }
53 return nowMinute;
54}
55
56export function useNowMinute(): string {
57 return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
58}