import { useEffect, useRef, useCallback } from 'react';
function useThrottleFn(fn, delay = 1000) {
const throttle = useRef<any>({ fn, timer: null });
useEffect(() => {
throttle.current.fn = fn;
}, [fn]);
return useCallback(
(...args) => {
if (!throttle.current.timer) {
throttle.current.timer = setTimeout(() => {
clearTimeout(throttle.current.timer);
delete throttle.current.timer;
}, delay);
throttle.current.fn(...args);
}
},
[delay]
);
}
export default useThrottleFn;
网友评论