Writing

Debounce and Throttle

文章發表於

Introduction

Imagine you're searching for something on a website, and every character you type immediately triggers an auto-suggest API call. This user experience might drive users away to competitors.

While the feature seems simple, improper handling can lead to a series of issues:

  • Server Overload: Frequent API requests can heavily burden the server. Without backend traffic control, it might even crash.
  • Race Condition: For example, if you type "apple is" and quickly change it to "banana", due to the response time difference, you might see recommendations for both "apple is" and "banana" on the screen.
  • Interface Lag: Immediate updates with each character input can cause the screen to flicker between "loading" and "displaying results", creating a jarring and uncomfortable user experience.

This article introduces two common solutions to such problems: Debounce and Throttle.

Throttle

What is Throttle?

Throttle is a technique that ensures a function is executed at most once in a specified interval, no matter how frequently the event is triggered. For example, if set to execute once per second, even if the event is triggered 100 times in a row, it will only process once per second, maintaining a fixed rhythm.

Core Principles

  • Execute the function immediately on the first call.
  • Set a cooling period.
  • Ignore or record new function calls during the cooling period.
  • (Optional) After the cooling period, execute the last function call again.

Use Cases

Throttle is suitable for scenarios requiring stable execution frequency, such as:

  • Scroll Events: Limit the frequency of scroll event processing.
  • Window Resize: Limit recalculations during window resizing.
  • Mouse Movement: Limit the processing frequency of mouse movement events.
  • Game Controls: Limit the processing frequency of key events.
  • Drag and Drawing Operations: Ensure 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);
};
}

Debounce

What is Debounce?

Debounce is another technique to control function execution frequency, ensuring the function is executed only once after the specified time since the last trigger. In simple terms, it only executes the function if there are no new triggers within a certain period; throttle, on the other hand, executes the function at fixed intervals, processing only periodically even if there are many triggers in between.

Core Principles

  • Set a cooling period on the first trigger.
  • During the cooling period, cancel the previous timer and reset the cooling period if there's a new trigger.
  • After the cooling period, execute the function and clear the timer.

Use Cases

Debounce is particularly suitable for scenarios where you want to wait for the user to stop before taking action, meaning it's best for events that are triggered frequently in a short time but where you only care about the "last" instance.

  • Search Suggestions: Initiate search requests only after the user stops typing.
  • Form Validation: Trigger validation only after the input field stops receiving input.
  • Auto-Save: Automatically save only after the user stops editing for a while.

Debounce Implementation

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

Throttle & Debounce Comparison

PatternUse WhenExample
DebounceOnly care about the final value after user stopsSearch suggestions, form validation, auto-save
ThrottleNeed regular 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