Skip to main content

Command Palette

Search for a command to run...

Debounce vs Throttle in JavaScript

Updated
4 min read

When building modern web applications, performance matters.
Events like scroll, resize, keypress, or API calls can fire hundreds of times per second, leading to laggy UI and unnecessary network requests.

Two powerful techniques to handle this are Debouncing and Throttling.

Let’s understand them intuitively, with diagrams, examples, and real-world use cases.


🔥 Why Do We Need Debounce & Throttle?

Imagine this code:

window.addEventListener("resize", () => {
  console.log("Resizing...");
});

If the user resizes the browser continuously, this function will be executed again and again — sometimes hundreds of times per second 😵‍💫.

This can:

  • Hurt performance

  • Flood APIs

  • Freeze the UI

👉 Debounce and Throttle help control how often a function executes.


🕰️ What is Debouncing?

Debouncing ensures that a function is executed only after a certain amount of time has passed since the last event.

“Wait until the user stops doing something.”

🧠 Real-World Analogy

Think of typing a message:

  • You type continuously

  • The action happens only after you stop typing


📊 Debounce Timeline

Key Presses:  | | | | |      |
Time (ms):    0 50 100 150 300
Debounce(300ms)
Output:                   ✅ Function runs once

💡 Common Use Cases

  • Search input (API calls)

  • Form validation

  • Auto-save

  • Resize events


🧩 Debounce Implementation (JavaScript)

function debounce(fn, delay) {
  let timer;

  return function (...args) {
    clearTimeout(timer);

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

🧪 Example: Search Input

function searchAPI(query) {
  console.log("Searching for:", query);
}

const debouncedSearch = debounce(searchAPI, 500);

input.addEventListener("input", (e) => {
  debouncedSearch(e.target.value);
});

👉 API call happens only after the user stops typing for 500ms


⚡ What is Throttling?

Throttling ensures that a function is executed at most once in a given time interval, no matter how many times the event occurs.

“Do it, but not too often.”


🧠 Real-World Analogy

Imagine a lift that can move once every 5 seconds, even if people keep pressing the button.


📊 Throttle Timeline

Scroll Events: | | | | | | | |
Throttle(300ms)
Output:        ✅     ✅     ✅

💡 Common Use Cases

  • Scroll handling

  • Button spam prevention

  • Window resize

  • Mouse movement tracking

  • Game mechanics


🧩 Throttle Implementation (JavaScript)

function throttle(fn, limit) {
  let lastCall = 0;

  return function (...args) {
    const now = Date.now();

    if (now - lastCall >= limit) {
      lastCall = now;
      fn.apply(this, args);
    }
  };
}

🧪 Example: Scroll Event

function handleScroll() {
  console.log("Scrolling...");
}

const throttledScroll = throttle(handleScroll, 300);

window.addEventListener("scroll", throttledScroll);

👉 Executes once every 300ms, no matter how fast you scroll


🆚 Debounce vs Throttle (Quick Comparison)

FeatureDebounceThrottle
ExecutionAfter inactivityAt fixed intervals
Best forSearch, input, resizeScroll, mouse move
API calls✅ Yes❌ Usually no
UI responsivenessWaitsImmediate but controlled

🎯 When to Use What?

✅ Use Debounce when:

  • You want the final result

  • User input matters more than intermediate events

  • Example: Search bar, form validation

✅ Use Throttle when:

  • You want continuous updates

  • Need performance + responsiveness

  • Example: Infinite scroll, window resize


🧠 Bonus Tip

Debounce = “Wait”
Throttle = “Limit”

If you remember just this line, you’ll never confuse them again 😉


🚀 Final Thoughts

Debouncing and throttling are essential performance optimization techniques every frontend developer should master.

They help you:

  • Build faster apps

  • Reduce unnecessary work

  • Improve user experience

If you’re working with React, Vue, or Vanilla JS, these concepts apply everywhere.


💬 Did this help?

Drop a ❤️ or comment on Hashnode if this cleared your confusion.
Happy coding! 🚀