Clear thinking · Useful delivery · Work built to last

PEN BEAM / COPY-READY EXAMPLE

Debounce a JavaScript Function

JavaScriptPerformanceAll modern browsers

Wait until rapid events settle before running expensive work such as search suggestions or resize calculations.

What this snippet does

Limits how often a function runs during rapid events by postponing execution until the event stream has been quiet for the configured delay.

JavaScript / source code
function debounce(callback, delay = 200) {
  let timeoutId;
  return function debounced(...args) {
    const context = this;
    window.clearTimeout(timeoutId);
    timeoutId = window.setTimeout(() => callback.apply(context, args), delay);
  };
}

const onResize = debounce(() => {
  document.documentElement.dataset.viewportWidth = String(window.innerWidth);
}, 180);
window.addEventListener('resize', onResize, { passive: true });

Where to place it

Place the function in the JavaScript module that owns the event behavior. In a WordPress theme, enqueue the file through the theme and use cache busting during development.

Back up the relevant file or settings first. Apply the change on staging, verify behavior, and retain a rollback path before production deployment.

What to check before deploying

  • Confirm the work does not need to run immediately on the first event; debounce intentionally waits until activity pauses.
  • Test mouse resizing, keyboard zoom and device orientation change, and verify the final update always occurs.
  • For components that mount and unmount, retain a cancellation/cleanup path so delayed callbacks do not act on removed UI.

Related snippets

Need this adapted to your project? Start a project