Debouncing

Suppose we need to develop a search component, basically an input box where we can search for stuff in a website. Or we want to save changes on a form, but only when the user is not actively working on those changes, as every "save" costs us a database trip. In such cases, it might be a good thing to know about Debouncing.

Debouncing is a programming pattern or a technique to restrict the calling of a time-consuming function frequently, by delaying the execution of the function until a specified time to avoid unnecessary CPU cycles, and API calls and improve performance.

HTML Code :

<input type="text" onkeyup="getData()" />

Without Debouncing : getData() will be called everytime a keyup event occurs - which is on typing each & every letter in the search box. This is a very time-consuming approach, keeping in mind that GenZ types real fast πŸ˜‰ and might stall the website's performance.

const getData = () => {
  console.log("calls API & fetches data!");
};

With Debouncing : getData() will be called if difference between two key up events is more than a certain time interval, say 500ms in our case. This is an optimized approach.

A Debounce function is a higher-order function that returns another function, to create closure around the function parameters (func, timeout) and the timer variable.

const customDebounce = function (fn, d) {
  let timer;
  return function () {
    let context = this;
    let args = arguments;

    clearTimeout(timer);
    timer = setTimeout(() => {
      getData.apply(context, arguments);
    }, d);
  };
};

const getDataOptimized = customDebounce(getData, 500);

Use Cases :

  • Search box Suggestions

  • Text field auto saves

  • Eliminating double-button clicks

References : Hell lot of articles on the Internet.

Last updated