The problem
When handling window resize, input events, need to prevent functions from being called too frequently
The solution
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}Parameters
funcfunctionFunction to debounce
delaynumberDelay time in milliseconds
Put it to work
// Handle window resize events
const handleResize = debounce(() => {
console.log('Window resized');
}, 300);
window.addEventListener('resize', handleResize);