Skip to content

Instantly share code, notes, and snippets.

@xmsi
Created January 1, 2025 15:06
Show Gist options
  • Save xmsi/5b5afd677bb781547747607166a3aa38 to your computer and use it in GitHub Desktop.
Save xmsi/5b5afd677bb781547747607166a3aa38 to your computer and use it in GitHub Desktop.
debounce for API limits

Debounce

Author: GPT-4o

Lodash's debounce function is used to limit how often a function is executed over time, even if it's called frequently. It's particularly helpful when you want to avoid unnecessarily calling a function multiple times in quick succession. This is especially useful for improving performance and user experience.

Example Scenario: Searching While Typing

Imagine you have a search bar where users type a query, and for each keystroke, a search request is sent to a server. If a user types "hello," five separate requests would be sent: one for "h," another for "he," then "hel," "hell," and "hello." This can overload the server and create lag.

Using debounce to Solve the Problem

With debounce, you can delay the execution of the search function until the user stops typing for a specified time (e.g., 300ms). This way, only one request is sent after the user has finished typing.

Here’s a simple example:

Without debounce

const handleInputChange = (value) => {
  console.log(`Searching for: ${value}`);
  // Simulate an API request
};

// Simulate typing "hello"
handleInputChange("h");
handleInputChange("he");
handleInputChange("hel");
handleInputChange("hell");
handleInputChange("hello");
// Logs 5 separate search requests

With debounce

// Import debounce from lodash
import debounce from 'lodash/debounce';

// Define the debounced function
const handleInputChange = debounce((value) => {
  console.log(`Searching for: ${value}`);
  // Simulate an API request
}, 300);

// Simulate typing "hello"
handleInputChange("h");
handleInputChange("he");
handleInputChange("hel");
handleInputChange("hell");
handleInputChange("hello");
// After 300ms pause, only one request is logged: "Searching for: hello"

Why Is It Useful in Inputs?

  1. Performance: Reduces the number of unnecessary operations (e.g., server requests) while typing.
  2. User Experience: Avoids lag or overloading the application by waiting until the user is done typing.
  3. Cleaner Output: Ensures only meaningful input (after the user pauses) is processed.

When to Use debounce:

  • Search bars: Limit API calls while typing.
  • Window resize events: Update UI or charts after the resizing stops.
  • Scroll events: Avoid frequent calculations during fast scrolling.
  • Auto-save: Delay saving until the user stops typing.

In short, use debounce whenever you need to wait for a user to "finish" an action before performing something resource-intensive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment