Debouncing and Throttling Javascript
Debouncing and Throttling are techniques to control the rate of function execution in response to frequent events like scrolling, resizing, or typing.
Debouncing:
- Delays function execution until after a specified time has passed without further calls.
- Useful when you want the function to run only once after an event stops.
- Example: Triggering an API search request only after the user stops typing.
function debounce(cb, delay) {
let timer;
return (...args) => {
clearTimeout(timer); // Clear any previously set timer
timer = setTimeout(() => {
cb(...args); // Call the function with the latest arguments
}, delay);
};
}
function apiCall() {
console.log("API Call at", new Date().toISOString());
}
const debouncedApiCall = debounce(apiCall, 1000); // Debounce with a 1-second delay
// Simulate frequent calls
debouncedApiCall();
debouncedApiCall();
ebouncedApiCall();
// Only the last call will execute after 1 second
Throttling:
- Limits function execution to once every specified interval, regardless of how often the event fires.
- Useful for cases where you want regular updates at a controlled rate.
- Example: Running a scroll handler every 200 milliseconds to avoid performance issues.
function throttle(cb, time) {
let lastCall = 0; // Track the last time the callback was executed
return (...args) => {
const now = Date.now(); // Current timestamp
if (now - lastCall >= time) {
lastCall = now; // Update the last call time
cb(...args); // Call the function
}
};
}
function apiCall() {
console.log("API Call at", new Date().toISOString());
}
const throttledApiCall = throttle(apiCall, 2000); // Throttle to 1 call per 2 seconds
// Simulate frequent calls
setInterval(() => {
throttledApiCall();
}, 500); // Attempt to call every 500ms
Summary:
- Debounce waits until the event stops to execute.
- Throttle executes at regular intervals during rapid events.