Throttling and debouncing are two JavaScript techniques for controlling how often a function is executed. Both are used to optimize performance, especially for event listeners triggered frequently (such as scroll, resize, or input events).
1. Throttling
Throttling
limits the number of times a function can be called over some time. With
throttling, the function can only execute at a fixed interval,
ignoring any additional calls during that time.
- Use Case: Ideal for events that
continuously fire, like scroll or resize, where updates need to
happen at regular intervals.
- Example: Updating the position of
an element on the screen while scrolling.
function throttle(func, delay) {
let lastcall = 0;
return function(...args)
{
const now
= new Date().getTime();
if (now -
lastCall >= delay) {
lastCall = now;
func.apply(this,
args);
}
};
}
Usage: If you wanted to log the scroll
position only every 500ms, you could use the throttle as
follows:
window.addEventListener('scroll', throttle(() =>
{
console.log('Scroll
position:', window.scrollY);
}, 500));
In this
example, the scroll event handler will only log the
position every 500 milliseconds, even if the scroll event triggers
continuously.
2. Debouncing
Debouncing
delays the execution of a function until after a specified period of time has
passed since the last time it was invoked. The function only executes after the
event stops firing for the given duration.
- Use Case: Suitable for cases where
you want the action to occur only after the event has stopped firing, such
as:
- input events for search boxes
(only search when the user stops typing)
- resize events (only resize after
resizing stops)
Example
function debounce(func, delay) {
let
timeout;
return function(...args)
{
clearTimeout(timeout);
timeout =
setTimeout(() => func.apply(this, args), delay);
};
}
Usage: For example, to debounce an
input field so that it only logs the value after the user has stopped typing
for 300ms:
const input = document.getElementById('searchInput');
input.addEventListener('input', debounce((event)
=> {
console.log('Search
for:', event.target.value);
}, 300));
In this
example, the function only executes after 300 milliseconds of no input,
reducing the number of times it is called as the user types.
Summary
- Throttling: Ensures a function
executes at most once in a specified time interval. Ideal for regular
updates based on continuous input (e.g., scroll, resize).
- Debouncing: Delays function execution
until the event has stopped firing for a certain period. Ideal for cases
where you want the action only after user input or actions stop (e.g., input, resize after resizing stops).
Both
techniques help improve performance by reducing unnecessary calls to functions,
especially in cases where events trigger rapidly.
No comments:
Post a Comment