DEV Community

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

Posted on • Edited 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.

Latest comments (34)

Collapse
 
oussamabouyahia profile image
Oussama Bouyahia

for submit button isn't a commun case , because its event handler could set states to emty strings , and when inputs are empty the button should be disabled.
However fr search input it is very useful and debouncing become imperative

Collapse
 
sandhya_ghadage_fcfe9abc2 profile image
Sandhya Ghadage

Thanks this is very useful 👍

Collapse
 
atuljalan profile image
Atul Jalan

Nice. There's also this good blog post that gives some more advanced techniques around debouncing.

Collapse
 
astrobotme profile image
Aditya

wonderfully explained 👏

Collapse
 
rama_subramanyam_b67e5a6d profile image
Rama Subramanyam

Thanks for the nice article and good picture.

Collapse
 
kevwasonga profile image
Kevin Wasonga

nice explanation with examples

Collapse
 
williamrjribeiro profile image
William R. J. Ribeiro

Nice explanation. Here's my favorive demo comparing debouncing and throttling: web.archive.org/web/20180324022838...

Collapse
 
yujeongkim profile image
yujeongKim

Thanks!

Collapse
 
iammtander profile image
Mitchell Mutandah

Nice breakdown. I can't wait to apply this! 😎

Collapse
 
paulo_reis_rosa profile image
Paulo Rosa

Really easy and simple explanation!