2024-09-02 react typescript 防抖封

2024-09-01  本文已影响0人  gdlooker
import { useEffect, useRef } from "react"

/**
 * 防抖
 *
 * @param {*} func
 * @param {*} wait
 * @param {*} immediate
 * @returns
 */
export const useDebounce = <T extends (...args: any) => any>(
  fn: T,
  time?: number,
): ((...args: any) => any) => {
  const timeoutIdRef = useRef<NodeJS.Timeout>()
  let delay = time || 300
  return (...args: any) => {
    if (timeoutIdRef.current) {
      clearTimeout(timeoutIdRef.current)
    }
    timeoutIdRef.current = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}

上一篇 下一篇

猜你喜欢

热点阅读