防抖和节流

防抖和节流

两者都是在一段时间内连续触发同一事件而为了避免事件处理函数频繁连续的调用而采取的解决方案。

防抖就是合并一段时间内连续的触发的事件

而节流控制相同事件之间必须要具有一定的时间间隔

打个比方,假如同一事件在10秒内触发了N次,如果采用防抖的方案,那么事件处理函数在10秒内只会触发一次。而如果采用节流的方案,可能就是在每间隔1秒的地方触发一次。

防抖的代码:

function debounce(fn, wait) {
  let timer = null;
  
  return (...argms) => {
    if (timer !== null) {
      clearTimeout(timer);
    }

    timer = setTimeout(() => fn(...argms), wait);
  };
}

节流:

function throttle(fn, delay) {
  let pre = null;

  return (...argms) => {
    const now = Date.now();
    const temp = pre;
    pre = now;

    if (temp === null || now - temp >= delay) {
      fn(...argms);
    }
  };
};
posted @ 2021-04-17 18:15  秦晓  阅读(90)  评论(0编辑  收藏  举报