| 19 | * approaches. |
| 20 | */ |
| 21 | export function useTime<T>(func: () => T, options: UseTimeOptions = {}): T { |
| 22 | const [computedValue, setComputedValue] = useState(() => func()); |
| 23 | const { disabled = false, interval = 1000 } = options; |
| 24 | |
| 25 | const thunk = useEffectEvent(func); |
| 26 | |
| 27 | useEffect(() => { |
| 28 | if (disabled) { |
| 29 | return; |
| 30 | } |
| 31 | |
| 32 | const handle = setInterval(() => { |
| 33 | const next = thunk(); |
| 34 | setComputedValue(() => next); |
| 35 | }, interval); |
| 36 | |
| 37 | return () => { |
| 38 | clearInterval(handle); |
| 39 | }; |
| 40 | }, [disabled, interval]); |
| 41 | |
| 42 | return computedValue; |
| 43 | } |