Debouncing and Throttling in JavaScript

Tvisha SharmaTvisha Sharma
2 min read

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! ๐Ÿš€

0
Subscribe to my newsletter

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

Written by

Tvisha Sharma
Tvisha Sharma