TS 防抖節流裝飾器

// 工具函數
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());
// });
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容