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