美文网首页
react useDebounce

react useDebounce

作者: Biao_349d | 来源:发表于2024-01-08 09:48 被阅读0次

hooks/useDebounce.ts

import { useRef } from 'react'

/* fn (Function): 要防抖动的函数。
[delay=0] (number): 需要延迟的毫秒数。
[options=] (Object): 选项对象。
[options.leading=false] (boolean): 指定在延迟开始前调用。
[options.trailing=true] (boolean): 指定在延迟结束后调用
*/
function useDebounce(fn: any, delay: any, options: { leading?: boolean; trailing?: boolean } = { leading: false, trailing: true }) {
  const { current } = useRef<any>({
    timer: null,
    dateTime: null
  })
  function f(...args: any[]) {
    const endTime = new Date().getTime()
    if (current.dateTime && options.leading && endTime - current.dateTime < delay) {
      return false
    } else if (options.leading) {
      current.dateTime = new Date().getTime()
      fn.bind(undefined, ...args)()
    }
    if (options.trailing) {
      if (current.timer) {
        clearTimeout(current.timer)
      }
      current.timer = setTimeout(fn.bind(undefined, ...args), delay)
    }
  }

  return f
}

export default useDebounce

相关文章

网友评论

      本文标题:react useDebounce

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