DEV Community

Discussion on: Throttling and Debouncing. Avoiding unnecessary API calls.

Collapse
 
hontas profile image
Pontus Lundin

Great post! I'm to a big fan of throttling/debouncing and I end up writing my own little helpers over and over.

I'll post my debounce function, happy to get feedback 😅 The benefit in this version is that it accepts arguments and get a proper this-binding when used as event handler - if you're into that sort of thing 😉

const debounce = (func, delay = 200) => {
  let timeoutId;

  return function() {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(this, arguments);
    }, delay);
  }
};

function search(evt) {
  console.log(evt.target === this); // true
}

const debouncedSearch = debounce(search, 500);
input.addEventListener("input", debouncedSearch);
Enter fullscreen mode Exit fullscreen mode

Thanks again!