Q27: Implement a throttle function from scratch.
Answer
Throttling limits how frequently a function executes. A common leading-edge throttle runs immediately and ignores calls made during the configured interval.
function throttle(fn, delay) {
let lastExecution = 0;
return function (...args) {
const now = Date.now();
if (now - lastExecution >= delay) {
lastExecution = now;
return fn.apply(this, args);
}
};
}
const logScroll = throttle(() => {
console.log("Scroll event handled");
}, 500);
window.addEventListener("scroll", logScroll);
Explanation
The wrapper records the time of the last execution. A new invocation executes only if the configured interval has passed.
This implementation is a basic leading-edge throttle. It does not schedule a trailing invocation, so the last event in a burst may never be processed. A production implementation may support both leading and trailing behavior, timer cleanup, and cancellation.
Key Takeaways
- Throttle limits execution frequency during repeated calls.
- Unlike debounce, a leading-edge throttle can execute before the event burst ends.