Improve App Performance: Learn About Debouncing

If you are a web developer and ever made a request to an API endpoint, it takes time. Consider an example, suppose if you have created an e-commerce application with a search bar on the top. If a user searches for any product, he/she hit the keystrokes from the keyboard and on every keystroke there is an API call which takes time to respond back with the data.

Problem

Without debouncing, you’re code might look like the one given below.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" placeholder="Enter text" id="input" />
    <script src="./debounce.js"></script>
  </body>
</html>

This is a simple HTML file having an input text field. Consider it as your search bar. Let’s write some javascript code to make an API call to an endpoint.

const input = document.getElementById('input');
const handlerFn = async(e)=>{
    const response = await fetch(`https://dummyjson.com/products/search?q=${e.target.value}`);
    const data = await response.json();
    console.log(data.products)
}
input.addEventListener('input', handlerFn);

This is a javascript code which makes a fetch request to an API endpoint and fetches the list of products on every time input value changes. Here is the result down below.

As you can see here, for every character in ‘phone‘ means for every keystroke there is an API call which degrades the performance of your application.

Solution

The solution is very simple, we’ll make request only once after the user stops typing. It means we need to provide a slight delay after the input event happens. For this we need to debounce the handlerFn .

What is Debouncing ?

Debouncing is a way to optimize application’s performance where you delay the execution of a function until after a certain amount of time has passed. Considering the above example we can delay the API calls after the user has stopped typing for 1000ms. Delay time could be adjusted according to the need.

const input = document.getElementById("input");

const handlerFn = async (e) => {
  const response = await fetch(
    `https://dummyjson.com/products/search?q=${e.target.value}`
  );
  const data = await response.json();
  console.log(data.products);
};

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

const debouncedFn = debounce(handlerFn, 500);

input.addEventListener("input", debouncedFn);

If you look at the code, we are passing our handlerFn as an arguement to a debounce function which delays the function to be invoked by 500ms. After debouncing we are getting these results.

Now you can see here, only after the user stopped changing the input field, after that there is a delay of 500ms. Only when the timer expires there is an API call made. This is how we reduced the number of function invocation by providing a slight delay to it and we have enhanced our appication’s performace.

Conclusion

Debouncing helps developers to optimize the performance of the application by reducing the number of function invocations. It prevents pointless network requests which consumes resources.

Hope this article clearly explained the concept of Debouncing!

0
Subscribe to my newsletter

Read articles from Vansh Singh Sura directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vansh Singh Sura
Vansh Singh Sura