极简代码实现节流Throttle和防抖Debounce

Favori,

Debounce

图:Nguyen Nhut

debounce防抖

function debounce(fn, delay) {
  let timmer = null;
  return function () {
    timmer && clearInterval(timmer);
    timmer = setTimeout(() => {
      fn.call(this, arguments);
    }, delay);
  };
}

throttle节流

function throttle(fn, delay) {
  let startTime = 0;
  return function () {
    let currentTime = new Date();
    if (currentTime - startTime > delay) {
      fn.call(this, arguments);
      startTime = currentTime;
    }
  };
}

CodePen示例