JavaScript Snippet

Debounce Function in JavaScript

Difficulty: Easy

Debouncing collapses a burst of calls into a single trailing invocation, which is the standard fix for noisy events like keystrokes, resize, and scroll. This snippet covers the canonical trailing-edge debounce, a variant with a manual `cancel` for component unmount, and a Promise-returning version that resolves only with the last call's result. Drop it into any UI handler that fires faster than the work it triggers.

Code Snippets
/

Debounce Function in JavaScript

Debounce Function in JavaScript

Debouncing collapses a burst of calls into a single trailing invocation, which is the standard fix for noisy events like keystrokes, resize, and scroll. This snippet covers the canonical trailing-edge debounce, a variant with a manual `cancel` for component unmount, and a Promise-returning version that resolves only with the last call's result. Drop it into any UI handler that fires faster than the work it triggers.

JavaScript
Easy
3 snippets
utility
code-template
performance-optimization
throttling

615 views

17

The classic implementation keeps one timer ID per debounced function and clears it on every call. As long as new calls keep arriving inside wait milliseconds, the timer keeps getting reset, so fn only fires after the burst goes quiet. Using fn.apply(this, args) preserves both the original this (handy when the debounced function is a class method) and the most recent argument set, which is what users expect for search-as-you-type. This is the version to default to for input handlers and resize listeners.