一、防抖
防抖:一连串操作只执行一次。通过设置一个延迟时间,如果这段时间没有再次执行操作则运行目标函数,否则重新计时。
下面是一个防抖函数代码:
            
            
              TypeScript
              
              
            
          
          let a=1;
const add = () => {
  a++;
};
const debounce = (fun: Function, delay: number) => {
  let timer: any = null;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fun();
    }, delay);
  };
};
const debounceAdd = debounce(add, 1000);
        二、节流
节流:立即执行目标函数,接着设定时间间隔,计时结束后才可再次执行目标函数。
            
            
              TypeScript
              
              
            
          
          let a = 0;
const add = () => {
  a++;
};
const throttle = (fun: Function, delay: number) => {
  let timer: any = null;
  return function () {
    if (!timer) {
      fun();
      timer = setTimeout(() => {
        fun();
        timer = null;
      }, delay);
    }
  };
};
const throttleAdd = throttle(add, 1000);