Skip to content
JavaScript

Debounce Function

Wait a period of time after an event triggers before executing; reset the timer if triggered again during the wait.

By EZ4Code Team
functionperformancedebounce

Code

function debounce(fn, delay = 300, immediate = false) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    if (immediate && !timer) {
      fn.apply(this, args);
    }
    timer = setTimeout(() => {
      timer = null;
      if (!immediate) fn.apply(this, args);
    }, delay);
  };
}

Explanation

Debounce is suitable for high-frequency scenarios like search input and window resize, avoiding frequent execution.

More JavaScript Snippets