注释
/**
- @example @limitFrequency('debounce') @limitFrequency('throttle')
- @params type:String enum('debounce','throttle')
- @params wait:Number 延迟时间默认500毫秒,也可自定义传入
- @note 支持箭头函数的写法了,且将截流throttle函数和防抖debounce函数合二为一
- 防抖 debounce: 任务被调用后, 在一定延迟后才执行, 若再次被调用, 则重新计算延迟时间
- 截流 throttle: 一定时间内, 任务不管被调用多少次, 只实际执行一次
*/
箭头函数写法
箭头函数写法 执行函数挂在 descriptor.initializer里,执行函数为return 出来的 function,且是匿名函数
descriptor.initializer = function(){
return function(){
console.log('执行')
}
}
普通函数写法
普通函数写法 执行函数挂在 descriptor.value上,执行函数就是该function
descriptor.value = function(){
console.log('执行')
}
调用方式
//上述所说的执行函数就是fn
@limitFrequency('debounce',1000)
fn = ()=>{
console.log('执行')
}
装饰器封装
export function limitFrequency(type, wait = 500) {
return function (pageInstance, funcName, descriptor) {
let timer = null;
let cacheValue = descriptor?.value || descriptor?.initializer()
const callBack = (...args) => {
if (type == 'debounce') {
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(() => {
cacheValue.apply(this, args)
clearTimeout(timer);
timer = null;
}, wait)
}
if (type == 'throttle' && !timer) {
timer = setTimeout(() => {
cacheValue.apply(this, args)
clearTimeout(timer);
timer = null;
}, wait)
}
};
if (cacheValue.name == funcName) {
descriptor.value = callBack
} else {
descriptor.initializer = () => callBack;
}
return descriptor;
}
}