JavaScript Reference ยท Promises and Async
clearTimeout() and clearInterval()
Reference for JavaScript clearTimeout() and clearInterval(): cancelling pending timers by id, clearing safely, debouncing, and cleanup patterns, with examples.
clearTimeout() cancels a timer created with setTimeout(), and clearInterval() cancels one created with setInterval(). Both take the id that the scheduling function returned. If the timer has not fired yet (or, for an interval, at any point), its callback never runs again.
Clearing is always safe: passing an id that has already fired, an unknown id, undefined or null does nothing and throws no error.
const id = setTimeout(save, 2000); clearTimeout(id);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
clearTimeout(timeoutId) clearInterval(intervalId)
| Name | Description |
|---|---|
timeoutId / intervalId |
The value returned by setTimeout() or setInterval(). Invalid values are ignored. |
Return value: undefined.
Usage notes
- Browsers share one pool of ids for timeouts and intervals, so
clearTimeout()andclearInterval()can technically cancel either kind. Do not rely on that; use the matching function for readability. - Store the id outside the callback (in a variable, object property or closure) so you can reach it later. A
const id = setInterval(...)can be used inside its own callback, because the callback runs after the assignment. - Debounce pattern: clear the previous timer, then start a new one, so only the last event in a burst triggers work (see the first example).
- Clear on cleanup. When a page section or component goes away, clear its timers, or callbacks keep touching removed elements.
- Clearing does not reset a running callback. If the callback is already executing, it finishes; clearing only prevents future calls.
- Reassign or null the id after clearing if later code checks whether a timer is active:
clearTimeout(id); id = null;. - In Node.js the ids are
Timeoutobjects; they work with these functions in the same way, and also offer.unref()and.refresh(). - Promise-based waits such as
await sleep(1000)cannot be cleared by themselves. Combine the timer with anAbortSignalif you need to cancel one.
Browser support
Both functions are supported in every browser, Web Worker and Node.js.