Q22 [Coding]: Write a throttle function implementation.
function throttle(fn, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
Throttling enforces a maximum execution rate, ensuring the function fires at most once per defined time interval.
Key Takeaways
- Executes function at regular, rate-limited time intervals.
- Ideal for scroll position tracking and window resize listeners.
Knowledge Check
How does throttling differ from debouncing?