david-s
3/7/2020 - 1:26 PM

Debounce - Useful for scroll events

Limit the amount a function gets called on scroll

  function debounce(callback, wait) {
    let timeout;
    return (...args) => {
      const context = this;
      clearTimeout(timeout);
      timeout = setTimeout(() => callback.apply(context, args), wait);
    };
  }

  function eventCounter(event) {
    console.count(event);
  }

  window.addEventListener('scroll', debounce(() => {
    eventCounter();
  }, 500));