import { useCallback, useEffect, useRef } from 'react';
import { useSyncedRef } from '../useSyncedRef/index.js';
const cancelTimeout = (id) => {
    if (id) {
        clearTimeout(id);
    }
};
export function useTimeoutEffect(callback, ms) {
    const cbRef = useSyncedRef(callback);
    const msRef = useSyncedRef(ms);
    const timeoutIdRef = useRef(null);
    const cancel = useCallback(() => {
        cancelTimeout(timeoutIdRef.current);
    }, []);
    const reset = useCallback(() => {
        if (msRef.current === undefined)
            return;
        cancel();
        timeoutIdRef.current = setTimeout(() => {
            cbRef.current();
        }, msRef.current);
    }, []);
    useEffect(() => {
        reset();
        return cancel;
    }, [ms]);
    return [cancel, reset];
}
