美文网首页
TS 防抖节流装饰器

TS 防抖节流装饰器

作者: MccReeee | 来源:发表于2021-09-11 01:34 被阅读0次
// 工具函数
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 防抖节流装饰器

  • ts防抖节流

    防抖动和节流本质是不一样的。防抖动是将多次执行变为最后一次执行,节流是将多次执行变成每隔一段时间执行。 使用

  • 防抖、节流

    1、防抖 2、节流(时间戳) 3、节流(定时器)

  • js的防抖和节流

    js的 防抖(debounce)和 节流(throttle ) 防抖和节流一般用于高频触发事件,属于浏览器性能优化...

  • 2019-03-27

    js的防抖和节流 据我所知防抖和节流都是为了优化作用,减轻浏览器和服务端的负担,防抖和节流俩个的英文要记住: de...

  • 函数节流与函数防抖

    节流与防抖的概念 函数节流与函数防抖的目的都是为了减少用户对服务器不必要的请求次数,以此提高服务器性能的函数。节流...

  • js 防抖 节流

    节流 防抖1 防抖2

  • 2019-04-24关于节流和防抖

    节流: 应用场景: 防抖: 应用场景: 1.节流 2.防抖

  • 谈谈js中的节流和防抖函数

    关于节流和防抖,这篇文章说的很好了,深入lodash源码分析防抖和节流深入篇 | Lodash 防抖和节流是怎么实...

  • 用js实现一个函数节流

    节流 防抖

网友评论

      本文标题:TS 防抖节流装饰器

      本文链接:https://www.haomeiwen.com/subject/qcsowltx.html