🚀 Introduction

When we write JavaScript, many of our functions run because of events like typing in a text box, scrolling on a page, or resizing a window. These events can happen very quickly and repeatedly. If we let the functions run every single time, the website may slow down or behave badly. To solve this, we use two techniques called debouncing and throttling. These help control how often a function is executed, making web apps faster and smoother.

⏱️ What is Debouncing?

Debouncing makes sure a function only runs after the user stops performing an action for a certain amount of time. It ignores all the quick, repeated actions and only cares about the final pause.

Think of it like this: If someone keeps ringing a doorbell many times, you only open the door once they stop ringing for a while.

Example:

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

// Example usage: Search input
const handleSearch = debounce((event) => {
  console.log("Search for:", event.target.value);
}, 500);

document.getElementById("search").addEventListener("input", handleSearch);

👉 Here, the search function will only run after the user stops typing for 500 milliseconds.

⏳ What is Throttling?

Throttling makes sure a function runs at most once every fixed period of time, no matter how many times the event happens. Instead of waiting for the action to stop, it executes regularly in intervals.

Think of it like this: If someone keeps ringing the doorbell non-stop, you decide to open the door only once every 10 seconds, no matter how many times they press it.

Example:

function throttle(func, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// Example usage: Scroll event
const handleScroll = throttle(() => {
  console.log("Scroll event triggered");
}, 1000);

document.addEventListener("scroll", handleScroll);

👉 This means the scroll function will only run once every second, even if the user scrolls very fast.

🔑 Key Differences Between Debouncing and Throttling

⌚ Execution Timing

🎯 Best Use Cases

⚡ Performance Impact

📘 Best Practices

📝 Summary

Debouncing and throttling are techniques that help control how often functions run in JavaScript when triggered by frequent events. Debouncing waits until the user has stopped performing an action, while throttling makes the function run at fixed intervals during the action. By using these techniques correctly, developers can make web apps run faster, smoother, and with fewer unnecessary function calls.