⚔️ Throttling vs Debouncing – DEV Community

⚔️ Throttling vs Debouncing – DEV Community


Feature Throttling Debouncing
Definition Executes function at regular intervals Executes function after a pause
Behavior Ignores calls made during the wait period Cancels previous calls and waits for inactivity
Use Case When you want to ensure the function runs every X ms When you want the function to run only after user stops typing/clicking
Example Resize event, scroll event, button spam prevention Search input, form validation, autocomplete
Code Trigger Runs periodically during the event stream Runs once after the event stream ends
Visual ⏱️⏱️⏱️… Controlled bursts ➖➖➖💥 Single delayed fire after calm



✅ Visual Example

Let’s say a user is typing:

"J" → "Jo" → "Joh" → "John"



🔁 Throttle (limit = 1s)

  • Calls function every 1s: might fire on “Jo”, then “John”



⏳ Debounce (delay = 1s)

  • Waits till user stops typing for 1s: fires only once on “John”



✅ Code Snippets Side by Side



🔁 Throttle

function throttle(func, limit) {
  let inThrottle;
  return function (...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}
Enter fullscreen mode

Exit fullscreen mode



⏳ Debounce

function debounce(func, delay) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), delay);
  };
}
Enter fullscreen mode

Exit fullscreen mode




🎯 When to Use What?

Scenario Use
Real-time scroll progress Throttle
Window resize Throttle
Button spam prevention Throttle
Search/autocomplete Debounce
Form input validation Debounce
Live filtering Debounce



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *