🔹 Debouncing:
Definition: Delays function execution until a certain time has passed since the last event call.
Use case: Useful when the action should be triggered only after the user stops doing something.
Example scenarios:
Auto-save after typing
Search-as-you-type
Behavior: Fires once after inactivity .
function debounce(func, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), delay);
};
}
🔹 Throttling:
Definition: Ensures a function is called at most once every specified interval , regardless of how many times the event occurs.
Use case: Useful for limiting execution frequency .
Example scenarios:
Scroll or resize event handling
Button spamming prevention
Behavior: Fires at regular intervals during activity.
function throttle(func, delay) {
let lastCall = 0;
return function (...args) {
const now = new Date().getTime();
if (now - lastCall >= delay) {
lastCall = now;
func(...args);
}
};
}
🔸 Summary:
Feature
Debouncing
Throttling
Triggers
After user stops triggering
At regular intervals
Execution Count
Once after inactivity
Limited, but regular
Use Case
Input fields, search boxes
Scroll, resize, mouse movement