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 |