Debouncing and throttling are techniques used to optimize the performance of functions triggered by events that occur frequently, such as scrolling, resizing, or typing. They help in managing how often these functions are executed, which can improve user experience and system performance. Here’s a detailed comparison of both techniques.
Debouncing
Debouncing is a technique that delays the execution of a function until a specified time has passed after the last event. It’s mainly used for events that fire rapidly, like scroll, resize, or button clicks. This prevents unnecessary function calls and improves performance.
- The function executes only after the user stops triggering the event.
- Multiple rapid events are collapsed into a single call.
- Example: If a user clicks 5 times in 100ms, the function won’t run during that burst.
- With a 2000ms debounce delay, the function runs 2 seconds after the final click.
- Helps reduce lag, avoid unnecessary processing, and optimize UI performance.
Advantages:
- Decreases the frequency with which a function is invoked, which can enhance performance and avoid pointless effort.
- Prevents pointless network and API requests, which can conserve resources and cut expenses.
- This can be utilized to handle frequent occurrences, such as scrolling or resizing, without taxing the system.
Disadvantages:
- This may cause a function to take longer to complete, which might be problematic when a quick answer is needed.
- The result can in missed events if the debounce time is too long.
Implement of Debouncing :
function debounce(func, delay) {
let timerId;
return function () {
const context = this;
const args = arguments;
clearTimeout(timerId);
timerId = setTimeout(function () {
func.apply(context, args);
}, delay);
};
}Example: In this example, we will use debouncing approach.
function delayFuncExec() {
console.log("I AM GFG ");
}
let timerId = setTimeout(delayFuncExec, 1000)
console.log("Timer Id: " + timerId);
Output
Timer Id: 2 I AM GFG
After 100 ms, delayFuncExec will be carried out. The integer produced by the setTimeout method will be stored in timerId.
Throttling
Throttling is a technique that limits how often a function can run over a set period, unlike debouncing which delays execution. It’s helpful for events like mousemove or keydown that fire continuously but don’t need to run the attached function every time.
- The function runs once per fixed interval regardless of how many times the event fires.
- It maintains a regular and controlled execution pattern.
- Reduces unnecessary calls and helps prevent performance slowdowns.
- Commonly used in scroll tracking, window resize handling, and real-time UI updates.
Advantages:
- This decreases the frequency of function calls, which can assist in avoiding performance problems and optimizing resource consumption.
- This is used to restrict the rate at which users enter data using their keyboards or mice in order to stop mistakes or undesirable behaviors.
Disadvantages:
- Given that the function will only be called at specific intervals, it could not respond right away.
- If the throttle time is too long, some events can be skipped, which could cause a loss of detail.
Syntax:
function throttle(callback, delay = 1000) {
let shouldWait = false;
return (...args) => {
if (shouldWait) return;
callback(...args);
shouldWait = true;
setTimeout(() => {
shouldWait = false;
}, delay);
};
}Example: In this example, we will use the throttling approach.
function throttle(func, delay) {
let lastCall = 0;
return function (...args) {
const now = new Date().getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
func(...args);
};
}
function logMessage(message) {
console.log(message);
}
const throttledLogMessage = throttle(logMessage, 1000);
// Logs 'Hello'
throttledLogMessage('Hello');
// Doesn't log anything
throttledLogMessage('World');
// Logs 'Delayed' after 2 seconds
setTimeout(() => throttledLogMessage('Delayed'), 2000);
Output
Hello Delayed
The throttle function in this example accepts two arguments: func, the function to be throttled, and delay, the minimum interval between calls to func. A new function that encapsulates func and executes the throttling logic is returned by the throttle function.
Difference between Debouncing and Throttling
| Aspect | Debouncing | Throttling |
|---|---|---|
| Definition | Delays execution until a period of inactivity | Limits execution to a fixed rate |
| Execution Timing | Executes once after the last event | Executes at regular intervals |
| Use Case | Ideal for handling events with intermittent pauses (e.g., typing, resizing) | Ideal for handling events with constant activity (e.g., scrolling, mouse movements) |
| Advantage | Reduces the number of function executions, which can improve performance and reduce unnecessary operations | Ensures function executes at a controlled rate, preventing performance degradation |
| Disadvantage | Delays function execution; might miss immediate feedback | Might miss events if the throttle interval is too long |