DEV Community

Cover image for Debounce vs Throttle in JavaScript: Real World Use Cases with Code
Sarvesh
Sarvesh

Posted on

Debounce vs Throttle in JavaScript: Real World Use Cases with Code

In full stack development, user interface performance isn’t just about aesthetics—it’s about responsiveness and resource management. Two critical tools in your toolkit for controlling how often functions are executed during high-frequency events are debounce and throttle.


🔍 What Are Debounce and Throttle?

Debounce

Delays execution until a specified time has passed since the last event. It’s ideal for events that shouldn’t fire until a user stops doing something.

Throttle

Ensures a function is only called once every specified interval, no matter how many times the event is triggered. Great for events that happen continuously but only need limited responses.


💡 Use Case Examples

Debounce – Real-Time Search

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

const handleSearch = debounce((e) => {
  fetchResults(e.target.value);
}, 300);

document.querySelector('#search').addEventListener('input', handleSearch);
Enter fullscreen mode Exit fullscreen mode

🧠 Why use it? Prevents overwhelming the API and enhances UX by only sending a request after typing has paused.

Throttle – Scroll-Based Animations

function throttle(func, limit) {
  let lastFunc;
  let lastRan;
  return function (...args) {
    const context = this;
    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(function () {
        if ((Date.now() - lastRan) >= limit) {
          func.apply(context, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  };
}

window.addEventListener('scroll', throttle(() => {
  console.log('Scroll event handled');
}, 200));
Enter fullscreen mode Exit fullscreen mode

🧠 Why use it? Keeps the UI responsive by limiting how often scroll logic executes.


🔄 Comparison Table

Feature Debounce Throttle
Trigger timing After delay (inactivity) At regular intervals
Ideal for Search inputs, resize events Scroll, mousemove, drag
Behavior Waits, then executes once Executes periodically

⚠️ Common Pitfalls and How to Avoid Them

  • Too aggressive debounce: User thinks the UI is unresponsive.
  • Too loose throttle: Not enough updates for smooth animation.
  • Forget context: Bind or use arrow functions to retain this.

✅ Key Takeaways

  • Use debounce when you want to delay execution until the user stops performing the action.
  • Use throttle when you want to allow execution at controlled intervals during continuous activity.
  • Implement these patterns to boost performance, improve UX, and reduce backend/API strain.

Top comments (0)