Codectionary / Developer documentation / JavaScript

Debouncing with Timers

Debouncing delays work until calls stop arriving for a chosen period. Each new call cancels the previous timeout and schedules another. A timeout specifies a minimum delay, not an exact execution time; busy event loops and background tabs can defer it.

Syntax

clearTimeout(timer);
timer = setTimeout(callback, delay);

Examples

Debouncing with Timers: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: After at least about 25 ms, only Search: cat is logged.

function debounce(callback, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => callback(...args), delay);
  };
}
const search = debounce(query => console.log("Search:", query), 25);
search("c");
search("ca");
search("cat");
  1. Expected result: After at least about 25 ms, only Search: cat is logged.
  2. The wrapper closes over a single timer shared by its calls.
  3. The example forwards arguments but intentionally does not preserve a method receiver; pass an arrow or bound callback if one is needed.

Best practices

  • Provide cancellation when a debounced task can outlive its component.
  • Do not debounce actions that must happen immediately, such as essential validation feedback on submission.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading