| 8 | setTickInterval: (ms: number) => void; |
| 9 | }; |
| 10 | export function createClock(tickIntervalMs: number): Clock { |
| 11 | const subscribers = new Map<() => void, boolean>(); |
| 12 | let interval: ReturnType<typeof setInterval> | null = null; |
| 13 | let currentTickIntervalMs = tickIntervalMs; |
| 14 | let startTime = 0; |
| 15 | // Snapshot of the current tick's time, ensuring all subscribers in the same |
| 16 | // tick see the same value (keeps animations synchronized) |
| 17 | let tickTime = 0; |
| 18 | function tick(): void { |
| 19 | tickTime = Date.now() - startTime; |
| 20 | for (const onChange of subscribers.keys()) { |
| 21 | onChange(); |
| 22 | } |
| 23 | } |
| 24 | function updateInterval(): void { |
| 25 | const anyKeepAlive = [...subscribers.values()].some(Boolean); |
| 26 | if (anyKeepAlive) { |
| 27 | if (interval) { |
| 28 | clearInterval(interval); |
| 29 | interval = null; |
| 30 | } |
| 31 | if (startTime === 0) { |
| 32 | startTime = Date.now(); |
| 33 | } |
| 34 | interval = setInterval(tick, currentTickIntervalMs); |
| 35 | } else if (interval) { |
| 36 | clearInterval(interval); |
| 37 | interval = null; |
| 38 | } |
| 39 | } |
| 40 | return { |
| 41 | subscribe(onChange, keepAlive) { |
| 42 | subscribers.set(onChange, keepAlive); |
| 43 | updateInterval(); |
| 44 | return () => { |
| 45 | subscribers.delete(onChange); |
| 46 | updateInterval(); |
| 47 | }; |
| 48 | }, |
| 49 | now() { |
| 50 | if (startTime === 0) { |
| 51 | startTime = Date.now(); |
| 52 | } |
| 53 | // When the clock interval is running, return the synchronized tickTime |
| 54 | // so all subscribers in the same tick see the same value. |
| 55 | // When paused (no keepAlive subscribers), return real-time to avoid |
| 56 | // returning a stale tickTime from the last tick before the pause. |
| 57 | if (interval && tickTime) { |
| 58 | return tickTime; |
| 59 | } |
| 60 | return Date.now() - startTime; |
| 61 | }, |
| 62 | setTickInterval(ms) { |
| 63 | if (ms === currentTickIntervalMs) return; |
| 64 | currentTickIntervalMs = ms; |
| 65 | updateInterval(); |
| 66 | } |
| 67 | }; |