// 工具函数
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...