Ticker

6/recent/ticker-posts

⏱️ Debouncing & Throttling in JavaScript — Control Events Like a Performance Pro

⏱️ Debouncing & Throttling in JavaScript — Control Events Like a Performance Pro

If you’ve ever added a search input or scroll listener and suddenly your app felt slow…

You’ve probably faced a performance problem caused by too many events firing too fast.

That’s exactly where debouncing and throttling come in.

These two techniques help you control how often a function runs — making your applications smoother, faster, and more efficient.

Let’s understand them the practical developer way.

🧠 Why Do We Need Debouncing & Throttling?

Some browser events fire extremely frequently:

  • scroll
  • resize
  • mousemove
  • input typing events

If your function runs on every trigger, it can execute dozens or even hundreds of times per second.

That means:

  • Performance drops
  • API calls increase
  • UI becomes laggy

Debouncing and throttling solve this problem.

🔁 What is Debouncing?

Debouncing ensures a function runs only after a certain delay once the event stops firing.

Think of it like waiting until the user finishes typing.

Example: Search Input

function debounce(fn, delay) {
  let timer;

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

const search = debounce(() => {
  console.log("Searching API...");
}, 500);

document.querySelector("#search").addEventListener("input", search);

Here:

  • The function runs only after typing stops for 500ms
  • Prevents unnecessary API requests

🚦 What is Throttling?

Throttling ensures a function runs at most once within a given time interval.

Instead of waiting, it limits execution frequency.

Example: Scroll Event

function throttle(fn, limit) {
  let inThrottle = false;

  return function (...args) {
    if (!inThrottle) {
      fn.apply(this, args);
      inThrottle = true;

      setTimeout(() => {
        inThrottle = false;
      }, limit);
    }
  };
}

const onScroll = throttle(() => {
  console.log("Scroll event handled");
}, 300);

window.addEventListener("scroll", onScroll);

Here:

  • Function executes once every 300ms
  • Perfect for animations or scroll tracking

⚖️ Debounce vs Throttle (When to Use)

Use Debounce when:

  • Waiting for user input to finish
  • Search suggestions
  • Form validation

Use Throttle when:

  • Tracking scroll position
  • Resize events
  • Continuous UI updates

A simple rule I follow:

👉 If the final action matters → debounce
👉 If continuous updates matter → throttle

🔥 Real-World Insight

In one project, we accidentally triggered an API call on every keystroke without debouncing. The server requests exploded instantly. Adding a 400ms debounce reduced calls by nearly 90% and made the UI feel instantly smoother.

Performance problems often aren’t about complex optimization — they’re about controlling execution frequency.

❌ Common Developer Mistakes

❌ Calling debounce/throttle inside event listeners repeatedly
❌ Forgetting closures store timer state
❌ Using throttle for search inputs
❌ Creating new debounced functions on every render

Always create the debounced/throttled function once and reuse it.

🚀 Best Practice Summary

✅ Use debounce for input fields and API searches
✅ Use throttle for scroll and resize events
✅ Reuse debounced functions instead of recreating them
✅ Keep delay values realistic (300–500ms usually works well)
✅ Optimize event-heavy features early

Reactions

Post a Comment

0 Comments