DEV Community

Cover image for Debouncing in JS: Building better web apps
Prathamesh Patil
Prathamesh Patil

Posted on

1

Debouncing in JS: Building better web apps

Have you ever been on a website, typed into a search bar, and noticed how the suggestions pop up in real-time without causing any lag? Or maybe you've filled out a form and seen the "Username already taken" message appear just as you're typing. Behind these seamless experiences is a powerful, often unsung hero of modern web development: debouncing.

What is Debouncing?

Debouncing is a programming technique that ensures a function is executed only after a specified period of inactivity. Imagine you're typing into a search bar. Without debouncing, every keystroke would trigger a function call, potentially overwhelming the system with redundant requests. Debouncing solves this by waiting for a pause in your typing before executing the function, ensuring only one request is sent.

How does it work?

At its core its controlling the frequency of function execution. But for a easier understanding lets take an example of a door bell. Suppose there's a door beer that rings after 3 seconds of inactivity. After the initial ring if users tries to ring the bell as many times it won't ring unless he decides to pass another 3 seconds.

In JavaScript, debouncing is commonly used with event listeners like input, scroll, or resize. Here's a basic implementation:

function debounce(callback, delay) {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      callback(...args);
    }, delay);
  };
}
Enter fullscreen mode Exit fullscreen mode

Lets understanding the different elements of this code:

  • debounce: The main function that creates and returns a debounced version of a given function.
  • callback: The function to be executed after the debounced delay.
  • delay: The amount of time (in milliseconds) the function should wait after the last event before executing the callback.
  • timeoutId is defined to hold the identifier of the timer created by setTimeout. This allows us to clear any ongoing timer before starting a new one, preventing unnecessary or repeated function executions.
  • clearTimeout cancels any existing timer associated with timeoutId.

Practical use cases

  • Search Input Fields: Live search is a classic use case for debouncing. Without it, every keystroke could trigger a database query, overwhelming the server. With debouncing, the function is called only after the user stops typing, reducing server load and improving performance.
const handleSearch = debounce((query) => {
  fetch(`https://api.example.com/search?q=${query}`)
    .then((response) => response.json())
    .then((data) => console.log(data));
}, 500);

document.getElementById("search").addEventListener("input", (e) => {
  handleSearch(e.target.value);
});
Enter fullscreen mode Exit fullscreen mode
  • Form Validation: Instant feedback on forms is great, but validating input on every keystroke can be resource-intensive. Debouncing allows you to delay validation until the user stops typing.
const validateInput = debounce((input) => {
  console.log(`Validating: ${input}`);
}, 400);

document.getElementById("username").addEventListener("input", (e) => {
  validateInput(e.target.value);
});
Enter fullscreen mode Exit fullscreen mode

Benefits of Debouncing

  • Performance Optimization: Reduces the number of function calls, preventing unnecessary computations or network requests.
  • Improved User Experience: Provides smoother, faster, and more responsive interactions.
  • Resource Efficiency: Reduces server load and conserves client-side resources, particularly important in large-scale applications.

.
.
.
.
.
Open to Suggestions
Have insights or additional tips on improving this blog? Feel free to share your feedback! Your input is invaluable for enhancing future content.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 👀

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more