调用hooksFn方法,通过传入一个普通的函数,返回一个带有防抖或者节流的方法
该方法接接收3个参数,返回一个新函数
param:fn
需要进行防抖节流的普通函数
param:time
防抖节流的时间
param:type
需要返回的函数时防抖还是节流 (notShake:防抖 throttle:节流)
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