四好公路
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

33 lines
769 B

/*
* create by Xumeng 2020/12/09
*/
import { useRef, useCallback } from 'react'
/**
* 函数节流- hooks
*
* 首次一定调用, 之后在 delay 时间后才会调用. 如果不指定 delay, 相当于直接调用.
*
* @param fn 函数回调
* @param delay 最小间隔, 单位: ms. 默认: 500ms.
*/
export function useThrottleCallback(fn, delay = true) {
const timeRef = useRef(0)
const throttleHandler = useCallback(
(...args) => {
if (!fn) return
const gap = delay === true ? 500 : delay
const now = Date.now()
if (now - timeRef.current <= gap) return
fn(...args)
timeRef.current = now
},
[fn, delay]
)
return delay ? throttleHandler : fn
}