Call the hooksFn method, pass in a normal function, and return a method with anti-shake or throttling
This method receives 3 parameters and returns a new function
param:fn
ordinary function that needs anti-shake throttling
param:time
anti-shake throttling time
param:type
anti-shake or throttling when the function needs to be returned (notShake: anti-shake throttle: throttling)
type Type = 'notShake' | 'throttle'
/**
* @params fn 要处理的方法; time 时间; type 返回的方法类型(notShake:防抖 throttle:节流);
* @return 返回一个防抖的函数 或者 节流的函数
*/
const hooksFn = (fn: Function, time:number, type: Type) => {
let timer:any = null
if (type === 'throttle') {
return function(...args: Array<any>) {
if (!timer) {
timer = setTimeout(() => {
clearTimeout(timer)
timer = null
}, time);
fn(...args)
}
}
} else {
return function(...args: Array<any>) {
clearTimeout(timer)
timer = null
timer = setTimeout(() => {
clearTimeout(timer)
timer = null
fn(...args)
}, time);
}
}
}
export default hooksFn