import React from "react";

type TimerHandle = ReturnType<typeof setTimeout>;

function useScheduler(
    callback: () => void,
    delay: number | null,
    schedule: (handler: () => void, timeout: number) => TimerHandle,
    clear: (handle: TimerHandle) => void,
) {
    const handleRef = React.useRef<TimerHandle | null>(null);
    const savedCallback = React.useRef(callback);

    React.useEffect(() => {
        savedCallback.current = callback;
    }, [callback]);

    React.useEffect(() => {
        if (delay === null) {
            return;
        }

        const run = () => {
            savedCallback.current();
        };

        handleRef.current = schedule(run, delay);

        return () => {
            if (handleRef.current !== null) {
                clear(handleRef.current);
                handleRef.current = null;
            }
        };
    }, [delay, schedule, clear]);
}

// 一个健壮，安全的 useTimeout
export function useTimeout(callback: () => void, delay: number | null) {
    useScheduler(callback, delay, setTimeout, clearTimeout);
}

// 一个健壮，安全的 useInterval
export function useInterval(callback: () => void, delay: number | null) {
    useScheduler(callback, delay, setInterval, clearInterval);
}