Middle
Implement a debounce function.
sobes.tech AI
Answer from AI
The debounce function allows limiting the frequency of calling another function, invoking it only after a certain amount of time has passed since the last call. This is useful, for example, for handling input events or window resize events.
Example implementation in JavaScript:
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// Usage:
const debouncedFunc = debounce(() => console.log('Called!'), 300);
window.addEventListener('resize', debouncedFunc);
In this example, the func function will be called only 300 ms after the last resize event.