美文网首页
useThrottleFn

useThrottleFn

作者: 王善良_ | 来源:发表于2023-10-17 17:53 被阅读0次
    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;
    
    

    相关文章

      网友评论

          本文标题:useThrottleFn

          本文链接:https://www.haomeiwen.com/subject/cwkqidtx.html