Middle
function debounce(callback, delay) {}
sobes.tech AI
Answer from AI
The debounce function limits the rate at which a given callback function is called. It delays the execution of callback until a specified delay interval has passed without new calls. This is useful, for example, when handling input or scroll events, to prevent the function from being called too frequently.
Example implementation in JavaScript:
function debounce(callback, delay) {
let timerId;
return function(...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
callback.apply(this, args);
}, delay);
};
}
// Usage:
const debouncedFunc = debounce(() => console.log('Called!'), 300);
window.addEventListener('resize', debouncedFunc);
In this example, callback will only be called after the resize event stops occurring for 300 ms.