美文网首页
useDebounceFn

useDebounceFn

作者: 王善良_ | 来源:发表于2023-10-17 17:54 被阅读0次
    import { useEffect, useRef, useCallback } from 'react';
    
    function useDebounceFn(fn, delay = 1000) {
      const debounce = useRef<any>({ fn, timer: null });
      useEffect(() => {
        debounce.current.fn = fn;
      }, [fn]);
    
      return useCallback(
        (...args) => {
          clearTimeout(debounce.current.timer);
          delete debounce.current.timer;
          debounce.current.timer = setTimeout(() => {
            debounce.current.fn(...args);
          }, delay);
        },
        [delay]
      );
    }
    
    export default useDebounceFn;
    
    

    相关文章

      网友评论

          本文标题:useDebounceFn

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