clearTimeout
Cancels a scheduled setTimeout.
Available since: Web API
Syntax
clearTimeout(timeoutId)Parameters
| Parameter | Type | Description |
|---|---|---|
| timeoutId | number | The id returned by setTimeout. |
Return value
undefinedReturns nothing.
Examples
A timer cancelled before it fires:
const id = setTimeout(() => console.log('never printed'), 500);
clearTimeout(id);
console.log('cancelled');Output:
cancelledDebounce — act only after a pause in input:
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
const search = debounce((text) => console.log('search:', text), 100);
search('a');
search('an');
search('ann');Output:
search: annNotes
Cancelling a timer that already fired or does not exist does nothing and throws no error.
See also
- setTimeout — Runs a function once after a delay.
- clearInterval — Stops a repeating setInterval.
Related recipes
In the tutorial
- Timers — The setTimeout and setInterval functions in JavaScript: delayed and repeated calls, arguments, cancelling a timer.