JavaScriptmediumJavaScript

Debounce Function

Prevents a function from being called too frequently, executes only the last call

01

The problem

When handling window resize, input events, need to prevent functions from being called too frequently

02

The solution

JavaScript
function debounce(func, delay) {
  let timeoutId;
  
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

03

Parameters

funcfunction

Function to debounce

delaynumber

Delay time in milliseconds

04

Put it to work

Example
// Handle window resize events
const handleResize = debounce(() => {
  console.log('Window resized');
}, 300);

window.addEventListener('resize', handleResize);