// 工具函数
const DELAY = 500;
// 防抖,装饰器
export function debounce(delay = DELAY) {
let timer: any = null;
return function(target, key, descriptor: PropertyDescriptor) {
const method = descriptor.value;
descriptor.value = function(...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
const result = method.call(this, ...args);
return result;
}, delay);
};
};
}
// 节流,装饰器
export const throttle = (delay = DELAY) => {
var previous = 0;
return function(target, key, descriptor: PropertyDescriptor) {
const method = descriptor.value;
descriptor.value = function(...args) {
let now = Date.now();
if (now - previous > delay) {
previous = now;
const result = method.call(this, ...args);
return result;
}
};
};
};
// 测试
// class C {
// @debounce(1000)
// static testDebounce(a) {
// console.log('防抖测试', a);
// }
// @throttle(1000)
// static testThrottle(a) {
// console.log('节流测试', a);
// }
// }
// window.addEventListener('resize', () => {
// //C.testDebounce(Date());
// // C.testThrottle(Date());
// });
TS 防抖节流装饰器
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 距离 第一次听到 节流与防抖 已经过去两年的时间,最近也是新看到一道题重新复习下老的知识点,并且提出新的解决方案。...
- 1. 在节流函数里,如何获取this问题 2. 在监听浏览器滚动中使用防抖,(removeEventListene...