What is debounce? How to implement debounce function

February 11, 2023

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

Debounce and throttle are the top ones that are asked frequently in the JavaScript coding interview. This blog post will talk about how to implement a debounce function.

What is debouncing

Debouncing is a technique used in computer programming to ensure that a function is not executed excessively. The idea behind debouncing is to limit the rate at which a function is executed.

Specifically, the event handler will be executed only when the event is not continuously triggered within a certain period of time. On the other hand, if the event is triggered more than once within the set time, the timing will be reset.

Before implementing the debounce function, let's first understand the use case of debounce.

Let's use the Google search box and list of search suggestions as an example. The screen is as follows, there is a search box and a search suggestion list, after the user enters text in the search box, the search suggestion list will display the results immediately; as long as the text in the search box is changed, the search suggestion list will also update the results immediately.

Google Search screen
Google Search screen

This seems to be an ideal design, right? Actually, there is a problem. If the user types many words in the search box, each word will triggers the API to update the search suggestion list. For example, if the user wants to search for javascript, the API will also be triggered 10 times because javascript has 10 characters. The first 9 times will be j, ja, jav and so on. It's not what the user wants so we actually don't really need to call the search API for those words.

In order to improve the user experience and reduce the number of redundant API calls, we can optimize it through debouncing.

The debounce function will accept two parameters

  • Delay time (ms)
  • the function to execute

Taking the example of the search box above, when the user continues typing, the function will not be executed. Only when the user stops typing text in the search box for a certain period of time, the function that triggers the API will be executed.

Implement debounce function

Let's look directly at the code first and see how much you can understand. Don’t worry if there is something you don’t understand, we will explain it line-by-line later.

function debounce(fn, delay = 500) {
  let timer;

  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn(...args);
    }, delay);
  };
}

Detailed explanation

// debounce function accepts two parameters
// the function to be executed
// the number of milliseconds to be delayed, here the default is 500 milliseconds
function debounce(fn, delay = 500) {
  let timer;

  // debounce function will eventually return a function
  return (...args) => {
    // Every time the debounce function is triggered, the previous timer will be cleared to avoid triggering the previous fn function
    clearTimeout(timer);
    // After clearing, reset a new the timer
    // When the delay time is up, execute fn
    timer = setTimeout(() => {
      fn(...args);
    }, delay);
  };
}

// updateDebounceText will be executed after a delay of 500 ms console.log('call api get search result')
const updateDebounceText = debounce((text) => {
  console.log("call api get search result");
}, 500);

// The search box listens to the input event, when the input changes
// trigger updateDebounceText function
searchInput.addEventListener("input", (e) => {
  updateDebounceText(e.target.value);
});
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee