DEV Community

Cover image for Debouncing in JavaScript
MFONIDO MARK
MFONIDO MARK

Posted on

3 1

Debouncing in JavaScript

Introduction

Debouncing is a common technique in JavaScript used to control how frequently a function is called, especially in response to events like scrolling or typing. It helps improve performance by reducing the number of function calls, which can be critical in scenarios where you want to avoid excessive processing or network(API) requests. In this article, we'll explore the concept of debouncing, and why it's important.

Understanding Debouncing

Imagine a scenario where you have a search input field on a web app, and you want to fetch search results from a server as the user types. Without debouncing, a request would be sent with every keystroke, potentially overwhelming the server and causing unnecessary network traffic. Debouncing helps solve this problem by delaying the execution of a function until a specified time has passed since the last triggering event.

Flow Chart Diagram of Debounce

The Debouncing Process

  1. An event, such as a keypress or mouse movement, triggers a function.

  2. Instead of executing the function immediately, a timer is set for a specific duration (the debounce delay).

  3. If another event occurs before the timer expires, the previous timer is canceled, and a new one is set.

  4. When the timer finally expires without any new events, the function is executed.

Use Cases for Debouncing

Debouncing is valuable in various scenarios:

1 . Search Suggestions: As mentioned earlier, it prevents excessive requests to a server when users type in a search bar.

2 . Infinite Scrolling: When users scroll through a long list, debouncing can be used to fetch more content only when they pause scrolling.

Implementing Debouncing in JavaScript

To implement debouncing in JavaScript, you can use either a basic function or a higher-order function. Below, we'll provide examples for both approaches.



function debounce(func, delay) {
  let timerId;

  return function (...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

// Usage:
const searchInput = document.getElementById('search-input');
const debounceSearch = debounce(search, 300);

searchInput.addEventListener('keyup', debounceSearch);

function search() {
  // Perform the search operation here
  console.log('Searching for:', searchInput.value);
}



Enter fullscreen mode Exit fullscreen mode
  • debounce is a function that takes a function func and a delay delay.

  • It returns a new function that clears the previous timer and sets a new one every time it's called.

  • The search function is our actual operation, and it is wrapped by the debounce function. It will only execute after the user stops typing for 300 milliseconds.

Higher-Order Function Example

A higher-order function version might look like this:



function debounce(func, delay) {
  let timerId;

  return function (...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

// Usage:
const searchInput = document.getElementById('search-input');
const debounceSearch = debounce(performSearch, 300);

searchInput.addEventListener('keyup', debounceSearch);

function performSearch() {
  // Perform the search operation here
  console.log('Searching for:', searchInput.value);
}



Enter fullscreen mode Exit fullscreen mode
  • debounce is still a function that takes a function func and a delay delay.
  • It returns a new function, which is assigned to debounceSearch. This function wraps the performSearch function.

The higher-order function approach allows you to debounce various functions without duplicating the debouncing logic.

Conclusion

Debouncing is a fundamental concept in JavaScript for improving performance in scenarios where you need to limit function execution. Whether you're building a search bar, implementing infinite scrolling, or handling other real-time user interactions, understanding and using debouncing can significantly enhance the user experience and optimize your application.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay