- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Throttle
JavaScript Performance
JavaScript Throttle
Throttling limits a function to running at most once in a given time window.
Debounce waits for calls to stop; throttle guarantees a steady trickle instead.
Scrolling is the classic case: you want updates, just not hundreds per second.
Example
Example
javascript
function throttle(fn, interval) {
let ready = true;
return function (...args) {
if (!ready) return;
ready = false;
fn(...args);
setTimeout(function () { ready = true; }, interval);
};
}
let calls = 0;
const throttled = throttle(function () { calls++; }, 10);
throttled();
throttled();
throttled();
console.log(calls);