Debouncing in JavaScript: Consider this before making API calls

JavaScript

5 mins read

Jan 24, 2023

In modern web development, performance matters—especially when building features like dynamic search or real-time filtering. One essential technique that can help is debouncing.

What Is Debouncing?

Debouncing is a programming concept used to control how often a function gets executed. It ensures that rapid, successive calls to a function are ignored unless there's a pause between them. In simpler terms, debouncing delays a function's execution until after a certain amount of time has passed since it was last called.

Real-Life Example

Let’s say you’re building a search bar that triggers an API call every time the user types. Without debouncing, the app might:

  • Send a request on every keystroke.
  • Overload the server with too many rapid API calls.
  • Waste resources and cause performance lags.

The Fix is to Debounce the Function

Debouncing introduces a delay. If the user continues typing within that delay, the timer resets. Only after the typing stops for a specified time (say 300ms), does the function actually run. This means only the final input triggers the API call, resulting in cleaner, more efficient execution.

blog-image-8

Example function of using debounce

// Function to create a debounced version of any function
function debounceFn(fn, t) {
  let id;
  return function (...args) {
    clearTimeout(id);
    id = setTimeout(() => fn(...args), t);
  };
}

// Usage example
const debounce = debounceFn(console.log, 100);
debounce('Hello world!');

This will delay the console.log by 100 milliseconds. If the function is triggered again before the delay expires, the previous call is canceled.

Debouncing is a small but powerful technique that keeps your applications smooth and resource-efficient. Whether you’re building live search, input validation, or scroll events, debouncing helps you do more with less. In short it reduces server load, boosts performance and responsiveness, and avoids unnecessary computation