Last Updated : 28 Jan, 2025
Throttling is a technique used to limit the number of times a function can be executed in a given time frame. It’s extremely useful when dealing with performance-heavy operations, such as resizing the window or scrolling events, where repeated triggers can lead to performance issues.
JavaScript
function throttle(fn, delay) {
let lastTime = 0;
return function (...args) {
let now = Date.now();
if (now - lastTime >= delay) {
fn.apply(this, args);
lastTime = now;
}
};
}
In this example
Certain user interactions, like scrolling or window resizing, trigger events multiple times per second. Executing event handlers at such a high frequency can lead to performance issues, including:
By throttling a function, we can ensure it executes at a controlled rate, reducing resource consumption and improving responsiveness.
How Throttling WorksThrottling works by restricting the execution of a function so that it runs at most once every predefined period, even if the event is triggered multiple times within that interval.
A simple way to implement throttling is by using setTimeout. The function execution is delayed and only runs after the specified time interval has passed.
JavaScript
function throttle(fn, delay) {
let isThr = false;
return function (...args) {
if (!isThr) {
fn.apply(this, args);
isThr = true;
setTimeout(() => {
isThr = false;
}, delay);
}
};
}
window.addEventListener('scroll', throttle(() => {
console.log('Scroll event triggered!');
}, 1000));
2. Using Date.now()
Another approach is to use Date.now() to keep track of the last execution time and determine when the function should be called again.
JavaScript
function throttle(fn, delay) {
let t = 0;
return function (...args) {
let now = Date.now();
if (now - t >= delay) {
fn.apply(this, args);
t = now;
}
};
}
window.addEventListener('resize', throttle(() => {
console.log('Resize event triggered!');
}, 500));
Difference Between Throttling and Debouncing
Both throttling and debouncing are techniques for controlling function execution, but they serve different purposes:
Feature Throttling Debouncing Execution Control Ensures function runs at most once per interval Delays function execution until event stops Best Use Cases Scroll events, API calls, keypress handling Search input, auto-save, form validation Frequency of Execution Runs at regular intervals Runs only once after a delay Use Cases of ThrottlingThrottling is commonly used in cases where frequent execution of a function can cause performance issues.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4