Writing

Debouncing and Throttling

文章發表於

Introduction

Imagine you're searching for something on a website, and every keystroke in the search box immediately triggers an API call for auto-suggestions. This kind of user experience might drive users away to competitors.

While the feature seems simple, improper handling can lead to several issues:

  • Server Overload: Excessive API requests can put significant strain on the server. Without proper rate limiting on the backend, it might even cause server crashes.
  • Race Conditions: For example, if you type "apple is" and immediately change to "banana," due to response timing differences, you might see recommendations for both "apple is" and "banana" appearing simultaneously.
  • UI Jank: When results update immediately with every keystroke, the interface constantly flickers between "loading" and "displaying results," creating a jarring and uncomfortable user experience.

This article introduces two common solutions to address such problems: Debouncing and Throttling.

Throttling

What is Throttling?

Throttling is a technique that ensures function execution is "evenly distributed across the timeline." No matter how frequently events are triggered, throttling guarantees that the function is called at most once within a specified interval. For example, if set to execute once per second, even if the event is triggered 100 times consecutively, it will only process once per second—maintaining a consistent rhythm.

Core Principles

  • Execute immediately on the first function call
  • Set a cooling period
  • Ignore or record new function calls during the cooling period
  • (Optional) Execute the previous function again after the cooling period ends

Use Cases

Throttling is ideal for scenarios where you need "consistent execution frequency," such as:

  • Scroll Events: Limiting scroll event processing frequency
  • Window Resize: Handling resize events with controlled recalculation frequency
  • Mouse Movement: Limiting mouse movement event processing
  • Game Controls: Restricting key event processing frequency
  • Drag and Drawing Operations: Ensuring smooth visual effects

Throttle Implementation

This basic implementation is sufficient for most simple scenarios, such as limiting button clicks or basic scroll event handling.

function throttle(func, wait) {
let shouldThrottle = false;
return function (...args) {
if (shouldThrottle) return;
shouldThrottle = true;
func.apply(this, args);
setTimeout(() => {
shouldThrottle = false;
}, wait);
};
}

Debouncing

What is Debouncing?

Debouncing is another technique for controlling function execution frequency. It ensures the function executes only once after the "last" trigger within a specified time period. Simply put, the function only executes when there are no new triggers for a certain duration. While throttling makes functions execute at fixed intervals (processing periodically even with multiple triggers), debouncing waits for activity to stop before executing.

Core Principles

  • Set a cooling period on the first trigger
  • Cancel previous timers and reset the cooling period if new triggers occur during the cooling period
  • Execute the function and clear the timer after the cooling period ends

Use Cases

Debouncing is particularly suitable for scenarios where you "wait for the user to stop before taking action." In other words, it's ideal for events that fire rapidly in short bursts, but where we only care about the "final" state.

  • Search Suggestions: Only initiate search requests after the user stops typing
  • Form Validation: Trigger validation after input stops
  • Auto-save: Automatically save content after the user stops editing for a period

Debounce Implementation

function debounce(func, wait) {
let timeId = null;
return function (...args) {
if (timeId) {
clearTimeout(timeId);
}
timeId = setTimeout(() => {
func.apply(this, args);
}, wait);
};
}

Throttling & Debouncing Comparison

PatternUse WhenExample
DebouncingOnly care about the final value after user stops operatingSearch suggestions, form validation, auto-save
ThrottlingNeed periodic updates during operationScroll position tracking, window resize handling, progress updates
If you enjoyed this article, please click the buttons below to share it with more people. Your support means a lot to me as a writer.
Buy me a coffee