🧠 Understanding Debounce and Throttle in JavaScript – With Real Use Cases

Noura MostafaNoura Mostafa
2 min read

In modern web apps, performance is everything. When working with events like typing, scrolling, or resizing, calling a function too frequently can slow down your app. That’s where debouncing and throttling come in.


πŸ” What is Debouncing?

Debounce delays the execution of a function until a specified time has passed since the last time it was invoked.

πŸ“Œ Use Case:

  • Search input fields

  • Form validation on typing

βœ… Example:

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

// Usage
const handleSearch = debounce(() => {
  console.log("Searching...");
}, 500);

⏱️ What is Throttling?

Throttle ensures that a function is only called once every X milliseconds, no matter how often the event is triggered.

πŸ“Œ Use Case:

  • Scroll events

  • Window resize

βœ… Example:

javascriptCopyEditfunction throttle(func, limit) {
  let lastFunc;
  let lastRan;
  return function (...args) {
    const context = this;
    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(function () {
        if ((Date.now() - lastRan) >= limit) {
          func.apply(context, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  };
}

// Usage
const handleScroll = throttle(() => {
  console.log("Scrolling...");
}, 200);

🧠 Key Differences

FeatureDebounceThrottle
FrequencyOnly after event stopsAt regular intervals
Use CaseTyping, search, resizeScrolling, mouse move
ExampleAuto-suggest fieldInfinite scroll pagination

βœ… When to Use Each?

  • Debounce: When you want to limit how often a function is called after an event finishes (e.g., typing).

  • Throttle: When you want to limit how often a function is called while the event is running (e.g., scrolling).


πŸ”š Conclusion

Debouncing and throttling are crucial for creating smooth and optimized web experiences. By understanding when and how to use them, you’ll write cleaner, faster, and more efficient code.

10
Subscribe to my newsletter

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

Written by

Noura Mostafa
Noura Mostafa

πŸš€ Aspiring Full-Stack Developer Blogger πŸ‘¨β€πŸ’» Passionate about web development and coding. ✍️ Sharing my journey through tech via CodeOdyssey 🌍 "The code is a journey, not a destination."