JS 实现防抖和节流

什么是防抖

限制执行次数,多次密集的触发只执行一次, 使用场景: input 输入框

什么是节流

限制执行频率,有节奏的执行, 使用场景:拖拽,resize

示例代码:

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

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

See the Pen JS 编程题 – 防抖和节流 by hjoker (@hjoker) on CodePen.