Debouncing vs Throttling in JavaScript β€” Explained with Real Examples

krishankrishan
2 min read

πŸ€” What Are Debouncing and Throttling?

If you've worked with JavaScript events like typing, scrolling, or resizing, you've probably noticed that these events fire many times per second. This can cause performance issues, especially when tied to expensive operations like API calls or DOM updates.

That’s where debouncing and throttling come in.


🧠 Debouncing

Debouncing delays the execution of a function until a certain time has passed without the event being triggered again.

πŸ“¦ Use case:

  • Search input fields

  • Button click prevention (double-submit)

πŸ”§ Example:

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

function searchQuery(value) {
  console.log("Searching:", value);
}

const debouncedSearch = debounce(searchQuery, 500);

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

🧠 How it Works:

  • Keeps resetting the timer until the user stops typing

  • Only calls the function after 500ms of "silence"


⚑ Throttling

Throttling ensures a function is only called once every N milliseconds, no matter how many times the event is triggered.

πŸ“¦ Use case:

  • Scroll events

  • Resize window

  • Button spam prevention

πŸ”§ Example:

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

function logScroll() {
  console.log("Scrolled:", window.scrollY);
}

window.addEventListener("scroll", throttle(logScroll, 200));

🧠 How it Works:

  • Executes the function immediately

  • Then ignores repeated triggers until 200ms has passed


βš”οΈ Debounce vs Throttle

FeatureDebounceThrottle
TimingDelays function until idleExecutes at regular intervals
Use CaseSearch, input fieldsScroll, resize, button limits
BehaviorFires once after delayFires once every interval

πŸ§ͺ Real World Example: Key Press Counter

let keyCount = 0;
function reportKeys() {
  console.log("Keys pressed:", keyCount);
  keyCount = 0;
}

const throttledReport = throttle(reportKeys, 1000);

document.addEventListener("keydown", () => {
  keyCount++;
  throttledReport();
});

βœ… Output:

Logs how many keys were pressed every 1 second, not on every key press.


πŸ’‘ Conclusion

  • Use debouncing when you want to wait for a pause before running a function (like search).

  • Use throttling when you want to limit how often a function runs (like scroll).

These tools are essential for building responsive, performant UIs in the frontend.


0
Subscribe to my newsletter

Read articles from krishan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

krishan
krishan

πŸ‘‹ Hey, I'm a Frontend Developer passionate about building clean, user-friendly interfaces. πŸš€ Learning and sharing everything from React, JavaScript, HTML/CSS to advanced topics like Data Structures, Algorithms & System Design. πŸ’» Documenting my journey from fundamentals to becoming a top-tier developer β€” one blog at a time. πŸ“š Join me as I break down complex topics into easy, practical lessons β€” with GitHub repos, code snippets, and real-world examples. πŸ” Consistent growth, community learning, and aiming high!