DEV Community

Cover image for JavaScript Debounce, Easiest explanation !(with Code)
jeetvora331
jeetvora331

Posted on • Updated on

JavaScript Debounce, Easiest explanation !(with Code)

Debouncing is a programming technique that helps to improve the performance of web applications by limiting the frequency of function calls. In this blog post, we will learn what debouncing is, why it is useful, and how to implement it in JavaScript with code examples.

What is debouncing?

Debouncing is a way of delaying the execution of a function until a certain amount of time has passed since the last time it was called. This can be useful for scenarios where we want to avoid unnecessary or repeated function calls that might be expensive or time-consuming.

For example, imagine we have a search box that shows suggestions as the user types. If we call a function to fetch suggestions on every keystroke, we might end up making too many requests to the server, which can slow down the application and waste resources. Instead, we can use debouncing to wait until the user has stopped typing for a while before making the request.

How to implement debouncing in JavaScript?

There are different ways to implement debouncing in JavaScript, but one common approach is to use a wrapper function that returns a new function that delays the execution of the original function. The wrapper function also keeps track of a timer variable that is used to clear or reset the delay whenever the new function is called.



const debounce = (mainFunction, delay) => {
  // Declare a variable called 'timer' to store the timer ID
  let timer;

  // Return an anonymous function that takes in any number of arguments
  return function (...args) {
    // Clear the previous timer to prevent the execution of 'mainFunction'
    clearTimeout(timer);

    // Set a new timer that will execute 'mainFunction' after the specified delay
    timer = setTimeout(() => {
      mainFunction(...args);
    }, delay);
  };
};


Enter fullscreen mode Exit fullscreen mode

Using wrapping function with debounce



// Define a function called 'searchData' that logs a message to the console
function searchData() {
  console.log("searchData executed");
}

// Create a new debounced version of the 'searchData' function with a delay of 3000 milliseconds (3 seconds)
const debouncedSearchData = debounce(searchData, 3000);

// Call the debounced version of 'searchData'
debouncedSearchData();


Enter fullscreen mode Exit fullscreen mode

Now, whenever we call debouncedSearchData, it will not execute searchDataimmediately, but wait for 3 seconds. If debouncedSearchData is called again within 3 seconds, it will reset the timer and wait for another 3 seconds. Only when 3 seconds have passed without any new calls to debouncedSearchData, it will finally execute searchData.

Image Representation

Image description

The image clearly shows that whenever the function is called again, the setTimeout() gets overwritten.

Here are three simple real life examples of debouncing:

  1. Submit button:When you click a submit button on a website, it doesn’t send the data immediately, but waits for a few milliseconds to see if you click it again. This way, it prevents accidental double submissions and errors.

  2. Elevator: When you press the button to call the elevator, it doesn’t move immediately, but waits for a few seconds to see if anyone else wants to get on or off. This way, it avoids going up and down too frequently and saves energy and time.

  3. Search box: When you type something in a search box, it doesn’t show suggestions on every keystroke, but waits until you stop typing for a while. This way, it avoids making too many requests to the server and improves the performance and user experience.

Conclusion

Debouncing is a useful technique to optimize web applications by reducing unnecessary or repeated function calls that might affect the performance or user experience. We can implement debouncing in JavaScript by using a wrapper function that returns a new function that delays the execution of the original function until a certain amount of time has passed since the last call.

I hope you found this blog helpful and learned something new about Debouncing in JavaScript. You can check out my article on Throttling in JavaScirpt Here.

Top comments (29)

Collapse
 
esponges profile image
Fernando González Tostado

I liked the other use cases. I usually only think in search inputs, but submit buttons should probably also be debounced.

Collapse
 
jeetvora331 profile image
jeetvora331

Thanks !

Collapse
 
ibrahimbagalwa profile image
Ibrahim Bagalwa

Nice one

Collapse
 
fredabod profile image
FredAbod

Thanks this is very usefull

Collapse
 
jeetvora331 profile image
jeetvora331

Thanks for your feedback!

Collapse
 
etharrra profile image
Thar Htoo

Thanks!

Collapse
 
jeetvora331 profile image
jeetvora331

Welcome!

Collapse
 
anuradha9712 profile image
Anuradha Aggarwal

Nice article!!

Collapse
 
majik11 profile image
MJ

does (...args) passed into the return function in debounce() represent the args in debounce(searchData, 3000) when called in debouncedSearchData?

Collapse
 
jeetvora331 profile image
jeetvora331

that represent the arguments passed in the main function (in this case it is searchData()). To keep the things simple, I have not used any arguments in the function searchData().

Collapse
 
gallih_armada_02b2de67e02 profile image
Gallih Armada

Thanks very insightfull bro

Collapse
 
jeetvora331 profile image
jeetvora331

Thanks for your feedback!

Collapse
 
rmaurodev profile image
Ricardo

Love the explanation. Great article.

Collapse
 
jeetvora331 profile image
jeetvora331

Thanks @ricardo

Collapse
 
j471n profile image
Jatin Sharma

I use the following approach, it's also the same:


/**
 * Debounces a function by delaying its execution until a certain amount of time has passed
 * since the last time it was invoked. Only the last invocation within the delay period will be executed.
 *
 * @param {Function} func - The function to be debounced.
 * @param {number} delay - The delay in milliseconds before the function is executed.
 * @returns {Function} - A debounced function.
 */
export function debounce(func, delay) {
  let timeoutId;

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

    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jeetvora331 profile image
jeetvora331

Nice one !

Collapse
 
paulo_reis_rosa profile image
Paulo Rosa

Really easy and simple explanation!