import { useRef, useEffect, useCallback } from 'react';import { loop } from "../utils/fn";export interface Opts { manual?: boolean;}const initialState = { start: loop, stop: loop };const useTimeout = (fn: () => void, delay: undefined | null | number, opts?: Opts) => { const timerRef = useRef<number>(null); const fnRef = useRef<() => void>(); const ref = useRef<{ start: () => void; stop: () => void }>(initialState); fnRef.current = fn; const stop = useCallback(() => { if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; } }, [timerRef]); const start = useCallback(() => { stop(); timerRef.current = setTimeout(() => { fnRef.current?.(); }, delay); }, [timerRef, delay]); useEffect(() => { const hasBack = delay === undefined || delay === null; ref.current = hasBack ? initialState : { start, stop }; if (!opts?.manual) { ref.current.start(); } return ref.current.stop; }, [delay]); return { ...ref.current } as const;};export default useTimeout;