· JavaScript · 3 min read
Debouncing and Throttling in JavaScript
Debounce and throttle are two key techniques in JavaScript used to control how often functions run, especially when they're called frequently.
These are often used to improve performance and user experience, especially when dealing with events like scrolling, resizing, or typing.
Debounce: Delayed Execution
Debouncing is a technique used to ensure that a function is not called too frequently. It’s typically used in scenarios where you want to wait for some time after the last event before taking an action.
This is useful when you’re dealing with events that can fire rapidly (such as scrolling or keyboard input) but you only want to respond to the final event after a certain delay.
Here’s a basic implementation of debouncing in JavaScript:
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func(...args);
}, delay);
};
}Debouncing and Throttling in JavaScript
// Run after 3 seocnds or (3000 milliseconds)
const runAfter3Seconds = debounce(function (name) {
console.log('Hi, ' + name);
}, 3000);
runAfter3Seconds('Babu Rao');
You can use this debounce function to wrap any function you want to debounce:
Use Cases for Debounce:
- Auto-complete suggestions: Delaying the search for auto-complete suggestions until the user stops typing.
- Resizing and scrolling: Efficiently handling window resizing and scrolling events.
- Button click events: Preventing multiple rapid clicks on a button that triggers an action.
Throttle: Rate-Limited Execution
Throttling is a technique used to ensure that a function is not called more often than a certain time interval.
Unlike debouncing, where the function is delayed until after the last event, throttling guarantees that the function is only executed at most once per specified interval.
function throttle(func, limit) {
let inThrottle;
return function (...args) {
if (!inThrottle) {
func(...args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
}
// call once every 3 seconds
const sayHi = throttle(function () {
console.log('Hi');
}, 3000);
// Call sayHi() every second:
setInterval(() => {
sayHi(); //This function will run once in 3 seconds
}, 1000);
Use Cases for Throttle:
- Scroll-based animations: Smooth scrolling animations are achieved by throttling the scroll event handler.
- User interface interactions: Rate-limiting actions like dragging and zooming in interactive UIs.
- Network requests: Preventing excessive API requests when a user rapidly interacts with a search or pagination feature.
Debounce vs. Throttle: When to Use Which
The choice between debounce and throttle depends on the specific use case and the desired behavior:
- Use debounce when you want to ensure that a function is executed only after a period of inactivity. It’s ideal for scenarios where you want a single delayed execution, such as auto-complete suggestions or preventing multiple button clicks.
- Use throttle when you want to limit the frequency of function execution. Throttling is suitable for scenarios where you want a controlled and consistent rate of execution, such as scrolling animations or network requests.