Implement a throttle function. This is a function that ensures another function is called at most once within a specified time period.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Logic/Approach:
Throttling ensures a function is called at most once within a specified time interval.
1. Maintain a flag (canRun) or a timestamp of the last execution.
2. When the throttled function is called, check if the cooldown period has passed.
3. If it has, execute the function and update the timestamp/flag.
4. If it hasn't, do nothing.
function throttle(func, delay) {
let canRun = true;
return function(...args) {
if (!canRun) {
return; // Do nothing if we are in the cooldown period
}
canRun = false;
const context = this;
// Execute the function
func.apply(context, args);
// Set a timeout to reset the 'canRun' flag after the delay
setTimeout(() => {
canRun = true;
}, delay);
};
}
// Example usage:
function onScroll() {
console.log('Scroll event handled!');
}
const throttledScrollHandler = throttle(onScroll, 200);
// Attach to scroll event:
// window.addEventListener('scroll', throttledScrollHandler);