useThrottleFn

2023-10-17  本文已影响0人  Asuler
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;

上一篇 下一篇

猜你喜欢

热点阅读