import { useCallback, useEffect, useRef } from "react";
export function useThrottleFn(fn) {
    var interval = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 100;
    var fnRef = useRef(fn);
    var timeoutRef = useRef(null);
    var lastArgsRef = useRef(null);
    var lastThisRef = useRef(null);
    var lastCallRef = useRef(0);
    fnRef.current = fn;
    var throttledFn = useCallback(function() {
        for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
            args[_key] = arguments[_key];
        }
        var now = Date.now();
        var remainingTime = interval - (now - lastCallRef.current);
        lastArgsRef.current = args;
        lastThisRef.current = this;
        if (remainingTime <= 0) {
            if (timeoutRef.current) {
                clearTimeout(timeoutRef.current);
                timeoutRef.current = null;
            }
            lastCallRef.current = now;
            fnRef.current.apply(lastThisRef.current, lastArgsRef.current);
        } else if (!timeoutRef.current) {
            timeoutRef.current = setTimeout(function() {
                lastCallRef.current = Date.now();
                timeoutRef.current = null;
                fnRef.current.apply(lastThisRef.current, lastArgsRef.current);
            }, remainingTime);
        }
    }, [
        interval
    ]);
    // 清理超时
    useEffect(function() {
        return function() {
            if (timeoutRef.current) {
                clearTimeout(timeoutRef.current);
            }
        };
    }, []);
    return throttledFn;
}
