Throttle Implementation
Limit function execution to once per time interval.
Code
JavaScript
function throttle(fn, limit) {
let inThrottle;
return function (...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
const throttledScroll = throttle(() => console.log("scroll"), 1000);Line-by-line explanation
- 1.inThrottle tracks whether we're in the cooldown period.
- 2.If not throttled, run the function immediately.
- 3.Set inThrottle to true and reset after limit ms.
- 4.Subsequent calls within limit are ignored.
Expected output
scroll (once per second)