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