DEV Community

Shashi Bhushan Kumar
Shashi Bhushan Kumar

Posted on

What is Debouncing in JavaScript, and why do we need it?

Debouncing is a technique where we delay the execution of a function
until the user stops performing an action.

In simple words:

Wait for the action to stop, then run the function.


Real-life Example (Search Box 🔍)

Imagine you are typing in a search box:

h

he

hel

hell

hello

If the website sends a request after every letter,
that means 5 requests for one word.

This is not efficient:

  • Too many server requests
  • Slower performance
  • Waste of resources

Now imagine this:

The website waits until you stop typing for 1 second,
then sends only one request.

That waiting behavior is called Debouncing.


Why Do We Use Debouncing?

  • To improve performance
  • To reduce unnecessary API calls
  • To prevent repeated execution
  • To make the application smoother

Simple Code Example

function debounce(func, delay) {
  let timer;

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

    timer = setTimeout(() => {
      func(...args);
    }, delay);
  };
}
// Example usage
const search = debounce(() => {
  console.log("Searching...");
}, 1000);
Enter fullscreen mode Exit fullscreen mode

One-line Summary

Debouncing waits for the action to finish before running the function.


## Next Question for You 👇
👉❓ What is the purpose of the map() method in JavaScript?

Top comments (0)