// refs: https://overreacted.io/making-setinterval-declarative-with-react-hooks/ import { useRef, useEffect, useState, } from 'react' import {safeInvoke} from '../help' import {AnyFunction} from '../ts-helper' type CallBack = AnyFunction export function useInterval(callback: CallBack, delay: number) { const [intervalId, setIntervalId] = useState(0) const savedCallback = useRef() useEffect(() => { savedCallback.current = callback }, [callback]) useEffect(() => { function tick() { safeInvoke(savedCallback.current) } if (delay && delay > 0) { const id = window.setInterval(tick, delay) setIntervalId(id) return () => clearInterval(id) } return undefined }, [delay]) return () => clearInterval(intervalId) }