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());
// });
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容