JavaScript Interview Question #121
What is throttling?
Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate
Quick Interview Answer
Throttling limits how frequently a function can execute during a period of continuous calls. Unlike debouncing, throttling can continue producing results at controlled intervals while the activity is still happening.
Detailed Explanation
Throttling limits how frequently a function can execute during a period of continuous calls. Unlike debouncing, throttling can continue producing results at controlled intervals while the activity is still happening.
It is useful for scroll, pointer-move, resize, and similar high-frequency events when periodic updates are required but executing on every event would be too expensive.
Code Example
function throttle(fn, delay) {
let allowed = true;
return (...args) => {
if (!allowed) return;
allowed = false;
fn(...args);
setTimeout(() => {
allowed = true;
}, delay);
};
}
const onScroll = throttle(
() => console.log("Scroll handled"),
200
);