Chapter XXIV · Advanced Concepts
Throttling
Throttling limits the execution of a function to at most once every specified time interval.
01 How It Works
Think of a machine gun firing at a steady, fixed rate limit per second regardless of trigger pulls.
Regardless of how many times an event triggers during the interval window, the function executes strictly at regular timed intervals.
example.js
function throttle(fn, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
window.addEventListener('scroll', throttle(() => console.log("Scrolled!"), 200));
1. Wrap target function in a throttling wrapper.
2. Check if a throttle lock flag is active.
3. Execute function and set timer lock for the specified limit.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
window.addEventListener("scroll", throttle(() => {
console.log("Scroll position checked");
}, 100));
Key Takeaway
Throttling ensures steady, controlled execution rates during high-frequency events like scrolling.