JavaScript Course
JavaScript
/
Advanced

Implement: Debounce

Definition

Write a function `debounce(func, wait)` that delays invoking the provided function until after `wait` milliseconds have elapsed since the last time the debounced function was invoked.

Explain Like I'm New

Debounce is an elevator door. You press the button, the door starts closing (timer starts). Just before it shuts, someone else presses the button. The door opens, and the timer RESTARTS. The elevator will not actually move until the timer finishes without anyone interrupting it.

Real World Example

Typing in a Search Auto-complete box. You don't want to fire an API request for every single letter ('a', 'ap', 'app', 'appl'). You debounce by 500ms. The API only fires 500ms after the user STOPS typing.

Common Use Cases

  • •Search bars
  • •Window resize events
  • •Auto-saving forms

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What is the difference between Debounce and Throttle?

intermediate

  • Write a basic Debounce implementation using closures.

advanced

  • How do you ensure the `this` context and `arguments` are passed correctly to the original function?

Flash Cards

Question

Debounce vs Throttle?

Click to reveal answer
Answer

Debounce groups a sudden burst of events into a SINGLE execution at the very end of the burst. Throttle ensures the function is executed steadily at a consistent rate (e.g., exactly once every 100ms) while the burst is happening.