| 9 | * @param delay - Interval duration in milliseconds. Pass `null` to disable. |
| 10 | */ |
| 11 | export const useIntervalTimer = ( |
| 12 | callback: () => void, |
| 13 | delay: number | null, |
| 14 | ) => { |
| 15 | const savedCallback = useRef<(() => void) | null>(null); |
| 16 | |
| 17 | // Remember the latest callback. |
| 18 | useEffect(() => { |
| 19 | savedCallback.current = callback; |
| 20 | }, [callback]); |
| 21 | |
| 22 | // Set up the interval. |
| 23 | useEffect(() => { |
| 24 | function tick() { |
| 25 | savedCallback.current?.(); |
| 26 | } |
| 27 | |
| 28 | if (delay !== null) { |
| 29 | const id = setInterval(tick, delay); |
| 30 | return () => clearInterval(id); |
| 31 | } |
| 32 | }, [delay]); |
| 33 | }; |