Debouncing and throttling are two techniques used in JavaScript to optimize the execution of functions that are triggered frequently, especially in response to user interactions like scrolling, resizing, or typing.
Debouncing
Debouncing ensures that a function runs only after a specified delay following the last trigger event. This prevents excessive function calls when an event fires repeatedly.
Real-world Example: Typing in a Search Bar
Imagine a user typing into a search bar. Without debouncing, every keystroke would trigger an API request, potentially overwhelming the server. Instead, with debouncing, the function waits until the user stops typing for a short period before making the request.
JavaScript Example (Debouncing a Search Input):
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
const searchAPI = (query) => {
console.log("Fetching search results for:", query);
};
const debouncedSearch = debounce(searchAPI, 500);
document.getElementById("searchBox").addEventListener("input", (event) => {
debouncedSearch(event.target.value);
});
🔹 Effect: The searchAPI
function executes only after the user stops typing for 500ms.
Throttling
Throttling ensures that a function executes at most once within a specific interval, even if it's triggered multiple times. This is useful for performance-intensive tasks like scrolling.
Real-world Example: Scroll Event Handling
Imagine a user scrolling through a website. Without throttling, the event listener could trigger dozens of times per second, potentially causing performance issues. Throttling ensures the function runs at a controlled rate.
JavaScript Example (Throttling a Scroll Event):
function throttle(func, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
func.apply(this, args);
}
};
}
const logScrollPosition = () => {
console.log("Scroll position:", window.scrollY);
};
const throttledScroll = throttle(logScrollPosition, 1000);
window.addEventListener("scroll", throttledScroll);
🔹 Effect: The logScrollPosition
function executes at most once per second, preventing excessive calls while scrolling.
Key Differences
Aspect | Debouncing | Throttling |
---|---|---|
Execution Timing | After a delay following the last trigger | At most once within a fixed time interval |
Use Case | Search inputs, button clicks | Scroll events, resize events |
Prevents | Rapid consecutive calls | Excessive function execution |
Both techniques improve performance by reducing unnecessary function calls, keeping your application smooth and efficient. Since you work with ReactJS, you might use debouncing for search inputs and throttling for window resize handlers inside React components.