Debouncing in Javascript

Have you noticed that once you type into an enquiry box on many sites like Google, Amazon, then there's a delay before the typeahead results appear. This functionality is frequently controlled by a function called a Debounce. The Debounce function delays the processing of the key up event until the user has stopped typing for a predetermined amount of time.

This prevents your application from wafting to process every event and also drastically reduces the number of API calls sent to your server. Processing every character as it’s entered could harm performance and add unnecessary load to your backend.

Implementing a debounce from scratch is a common interview question. It tests your understanding of intermediate and advanced JavaScript concepts such as: async programming, callbacks, scope, and closures. It is also a practical solution used in real-world applications to improve performance and demonstrates that you understand the javascript concepts real good.

Let's see it through an example :-

const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      timeout = null;
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

Let's understand this code step by step :-

let timeout;

We declare a variable to store the timer returned by setTimeout function. This becomes useful if we want to clear the timer at a later point when again the debounce function fires.

return function executedFunction(...args) {

This is the function that is returned and will be executed many times. We use spread (...args) to capture any number of parameters we want to pass.

const later = () => {

The callback function to be executed after the debouncing time has elapsed.

timeout = null;

null timeout to indicate the debounce ended.

func(...args);

Execute the callback function with the arguments.

};
clearTimeout(timeout);

This will reset the function waiting to be executed. This is the step that prevents the function from being executed because it will never reach its completion i.e. timer does not gets completed and we clear it.

timeout = setTimeout(later, wait);

Restart the debounce waiting period.

That sums up the debouncing function.