Skip to main content

Command Palette

Search for a command to run...

Debouncing and Throttling in JavaScript

Published
2 min read
Debouncing and Throttling in JavaScript

When we build web applications, some events like scrolling, resizing, or typing can fire hundreds of times per second. If we handle every single event directly, it can slow down our app.

That’s where Debouncing and Throttling come in — two techniques to control how often a function runs.

The Problem

Imagine you’re typing in a search bar. If the app makes a network request after every keystroke, the server will get overloaded.

Or, imagine tracking the user’s scroll position. Without control, the function may run thousands of times in just a few seconds.

👉 We need a way to limit function calls.

🕒 Debouncing

Definition: Debouncing makes sure that a function runs only after a certain time has passed without it being called again.

✅ Real-life Example:

  • Think about pressing the elevator button. No matter how many times people press it, the elevator comes only once after a pause.

Example in Code:

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

// Usage: Search bar
const searchInput = document.getElementById("search");
searchInput.addEventListener("keyup", debounce((e) => {
  console.log("Searching for:", e.target.value);
}, 500));

👉 Here, the search happens only when the user stops typing for 500ms.

⏳ Throttling

Definition: Throttling makes sure a function runs at most once in a fixed interval, even if the event keeps happening.

✅ Real-life Example:

  • Think about a speed radar on the road. Even if 100 cars pass per second, the radar only records one car every few seconds.

Example in Code:

function throttle(func, limit) {
  let lastCall = 0;
  return function(...args) {
    const now = Date.now();
    if (now - lastCall >= limit) {
      lastCall = now;
      func.apply(this, args);
    }
  };
}

// Usage: Scroll tracking
window.addEventListener("scroll", throttle(() => {
  console.log("Scroll position:", window.scrollY);
}, 1000));

👉 Here, no matter how much you scroll, the function runs only once every 1 second.

⚖️ Debounce vs Throttle

FeatureDebounce 🕒Throttle ⏳
When it runsAfter pauseAt regular intervals
Use CaseSearch input, form validationScroll tracking, window resize
ExampleWait until user stops typingLog scroll every 1 sec

✅ Conclusion

  • Debouncing waits until things calm down before running.

  • Throttling allows execution but only at controlled intervals.

Both are must-know techniques to improve performance in real-world apps. Next time you build a search bar or track scrolling, try using one of them! 🚀