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());
// });

你可能感兴趣的:(TS 防抖节流装饰器)