Both debouncing and throttling are techniques used to control the frequency of function execution. They are helpful for optimizing performance, especially in event-driven applications like scrolling, resizing, and user input.
Table of Contents
🔹 1. Debouncing – “Wait Until I Stop”
Debouncing ensures that a function runs only AFTER a certain delay, once the user stops triggering an event.
📌 Example Use Case:
- Search input box (Wait for the user to stop typing before making an API call)
- Window resizing (Trigger event only after resizing stops)
✅ Implementation of Debouncing
function debounce(func, delay) { let timer; return function (...args) { clearTimeout(timer); // Clear previous timer timer = setTimeout(() =>; func.apply(this, args), delay); }; } // Example: Search input event listener function fetchData(query) { console.log("Fetching data for:", query); } const debouncedFetch = debounce(fetchData, 500); document.getElementById("search").addEventListener("input", function (e) { debouncedFetch(e.target.value); }); </code>
🏆 How It Works?
- Each keystroke resets the timer.
- The
fetchData
function is called only after the user stops typing for 500ms.
🔹 2. Throttling – “Run Every X Seconds”
Throttling ensures that a function runs at most ONCE every specified interval, even if the event is triggered multiple times.
📌 Example Use Case:
- Window scroll event (Execute a function every 300ms while scrolling)
- Button click event (Prevent spamming of API calls)
✅ Implementation of Throttling
function throttle(func, interval) { let lastTime = 0; return function (...args) { let now = Date.now(); if (now - lastTime >= interval) { func.apply(this, args); lastTime = now; } }; } // Example: Handling scroll event function logScroll() { console.log("Scroll event triggered at", new Date().toLocaleTimeString()); } const throttledScroll = throttle(logScroll, 1000); window.addEventListener("scroll", throttledScroll); </code>
🏆 How It Works?
- The function executes only once every 1000ms (1 second), even if scrolling happens continuously.
🎯 Key Differences Between Debouncing & Throttling
Feature | Debouncing | Throttling |
---|---|---|
Definition | Executes the function only after a pause | Executes the function at fixed intervals |
Best For | User input handling (e.g., search bar, resize) | Event rate limiting (e.g., scrolling, API calls) |
Execution Frequency | Only runs once after the delay | Runs at regular intervals |
Example | Waiting before calling an API after typing | Running a function every 1s during scrolling |
🎯 When to Use What?
Scenario | Use |
---|---|
Search bar input (API calls after typing stops) | ✅ Debounce |
Window resize (Execute after user stops resizing) | ✅ Debounce |
Scroll event (Executing code every X ms while scrolling) | ✅ Throttle |
Preventing spam clicks on a button | ✅ Throttle |