forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-interval.ts
More file actions
67 lines (55 loc) · 1.75 KB
/
Copy pathuse-interval.ts
File metadata and controls
67 lines (55 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { useContext, useEffect, useRef, useState } from 'react'
import { ClockContext } from '../components/ClockContext.js'
/**
* Returns the clock time, updating at the given interval.
* Subscribes as non-keepAlive — won't keep the clock alive on its own,
* but updates whenever a keepAlive subscriber (e.g. the spinner)
* is driving the clock.
*
* Use this to drive pure time-based computations (shimmer position,
* frame index) from the shared clock.
*/
export function useAnimationTimer(intervalMs: number): number {
const clock = useContext(ClockContext)
const [time, setTime] = useState(() => clock?.now() ?? 0)
useEffect(() => {
if (!clock) return
let lastUpdate = clock.now()
const onChange = (): void => {
const now = clock.now()
if (now - lastUpdate >= intervalMs) {
lastUpdate = now
setTime(now)
}
}
return clock.subscribe(onChange, false)
}, [clock, intervalMs])
return time
}
/**
* Interval hook backed by the shared Clock.
*
* Unlike `useInterval` from `usehooks-ts` (which creates its own setInterval),
* this piggybacks on the single shared clock so all timers consolidate into
* one wake-up. Pass `null` for intervalMs to pause.
*/
export function useInterval(
callback: () => void,
intervalMs: number | null,
): void {
const callbackRef = useRef(callback)
callbackRef.current = callback
const clock = useContext(ClockContext)
useEffect(() => {
if (!clock || intervalMs === null) return
let lastUpdate = clock.now()
const onChange = (): void => {
const now = clock.now()
if (now - lastUpdate >= intervalMs) {
lastUpdate = now
callbackRef.current()
}
}
return clock.subscribe(onChange, false)
}, [clock, intervalMs])
}