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");- Expected result: After at least about 25 ms, only Search: cat is logged.
- The wrapper closes over a single timer shared by its calls.
- 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