Debouncing in Javascript

Debouncing in Javascript

Debouncing makes sure that a function does not get called until after a specified period of time has elapsed since the last time it has been called. This is useful in situations where unnecessary calls to expensive operations could be made.

Just as an instance: think of a search box that gives suggestions while one types; if for every keypress a function is called to fetch suggestions, too many requests are generated on the server, obviously slowing down the application and wasting resources. The debounce can be applied so that the request is fired only after the user stops typing for a certain delay.

const createDebounceFunction = (actionFunction, delay) => {
  let timer;

  return function (...args) {
    clearTimeout(timer);

    timer = setTimeout(() => {
      actionFunction(...args);
    }, delay);
  };
};

 

 

 

Share: