How do I debounce or throttle functions

Debouncing and throttling are two techniques used in JavaScript to limit the rate at which a function is executed. They can enhance performance and improve the user experience by reducing the frequency of function calls during events like scrolling or resizing.

Debounce Function

The debounce function ensures that a function is only executed once after a specified delay, regardless of how many times it is triggered within that delay.

function debounce(func, delay) { let timeout; return function(...args) { const context = this; clearTimeout(timeout); timeout = setTimeout(() => func.apply(context, args), delay); }; } // Example usage const logResize = debounce(() => { console.log('Window resized!'); }, 500); window.addEventListener('resize', logResize);

Throttle Function

The throttle function limits the execution of a function to a fixed interval, ensuring that it cannot be called again until the specified time has passed.

function throttle(func, limit) { let lastFunc; let lastRan; return function(...args) { const context = this; if (!lastRan) { func.apply(context, args); lastRan = Date.now(); } else { clearTimeout(lastFunc); lastFunc = setTimeout(() => { if ((Date.now() - lastRan) >= limit) { func.apply(context, args); lastRan = Date.now(); } }, Math.max(limit - (Date.now() - lastRan), 0)); } }; } // Example usage const logScroll = throttle(() => { console.log('Window scrolled!'); }, 1000); window.addEventListener('scroll', logScroll);

debounce throttle JavaScript optimization function control performance improvement