Implement throttle
Throttling is a technique that ensures that the function does not execute more than once in a specified time period.
This is useful for managing the performance of functions that could be triggered frequently.
You are required to implement throttle(fn, delay)
decorator function.
Example
function throttle(fn, delay) {
// Your implementation
}
const print = () => {
console.log("print");
};
const fn = throttle(print, 1000);
// fn function will be called once in a second on window resize
window.addEventListener("resize", fn);
Solution
function throttle(fn, delay) {
// Initialize a timer variable for managing the throttling
let timer = null;
// Return a new function that encapsulates the throttling logic
return (...args) => {
// if timer is already running, then just skip fn call
if (timer) return;
// Set a timer that delays the function execution
timer = setTimeout(() => {
// Execute the original function with the provided arguments
fn(...args);
// Clear the timer after the function executes and reset it to null
clearTimeout(timer);
timer = null;
}, delay);
};
}
const print = () => {
console.log("print");
};
const fn = throttle(print, 1000);
// fn function will be called once in a second on window resize
window.addEventListener("resize", fn);