0
点赞
收藏
分享

微信扫一扫

事件的节流(throttle)与防抖(debounce)

scroll 事件,resize 事件、鼠标事件(比如 mousemove、mouseover 等)、键盘事件(keyup、keydown 等)都存在被频繁触发的风险。频繁触发回调导致的大量计算会引发页面的抖动甚至卡顿。

为了规避这种情况,我们需要一些手段来控制事件被触发的频率。然而,节流(throttle)与防抖(debounce)是我们在日常开发中常用的优质代码片段,能够给我们的项目带来性能的提升。


节流(throttle)与防抖(debounce)的本质

这两个东西都以闭包的形式存在。

它们通过对事件对应的回调函数进行包裹、以自由变量的形式缓存时间信息,最后 setTimeout 来控制事件的触发频率


节流(throttle)

节流(throttle) 的中心思想在于:在某段时间内,不管你触发了多少次回调,我都只认第一次,并在计时结束时给予响应。

function throttle(fn: Function, delay: number) {
  let timer: any = null;

  return function () {
    if (timer) return;
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null;
    }, delay);
  };
}



防抖(debounce)

防抖(debounce)的中心思想在于:我会等你到底。在某段时间内,不管你触发了多少次回调,我都只认最后一次

function debounce(fn: Function, delay: number) {
  let timer: any = null;

  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null;
    }, delay);
  };
}

举报

相关推荐

0 条评论