Node.js Reference ยท Globals and Console
Node.js clearTimeout(), clearInterval() and clearImmediate()
Reference for clearTimeout(), clearInterval() and clearImmediate() in Node.js: what they accept, why they never throw, and how to cancel timers safely.
Three global functions cancel scheduled work: clearTimeout() cancels a timer created by setTimeout(), clearInterval() stops one created by setInterval(), and clearImmediate() cancels a callback from setImmediate(). Each takes the object returned when the work was scheduled.
They are deliberately forgiving. Passing undefined, a timer that already fired, or one that was already cleared does nothing and never throws, so cleanup code can call them without checking first.
const timer = setTimeout(() => console.log('x'), 1000); clearTimeout(timer);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
clearTimeout(timeout) clearInterval(timeout) clearImmediate(immediate)
| Name | Description |
|---|---|
timeout |
The Timeout object returned by setTimeout() or setInterval(), or its numeric id (+timer). |
immediate |
The Immediate object returned by setImmediate(). |
Returns: undefined.
Errors: none. Invalid arguments are ignored.
Usage notes
- Clear what you started. A pending
setIntervalkeeps the process alive; always clear it on shutdown or when the owning object is closed. - Never throws:
undefined,null, plain objects and already-finished timers are ignored. This makes it safe to writeclearTimeout(this.timer)before the timer is ever set. - Reset the variable. After clearing, set the stored handle to
undefinedornullso you can tell later that nothing is scheduled. clearTimeoutandclearIntervalare interchangeable in Node.js because both timer kinds share one implementation. Browsers behave the same way, but pick the matching name for clarity.clearImmediateis separate: passing anImmediatetoclearTimeoutdoes not cancel it.- Numeric ids: the
Timeoutobject converts to a number, and Node.js accepts that number, which is helpful for code ported from browsers. Prefer keeping the object. - Debounce pattern: clear the previous timer, then start a new one on every event. Use
timer.refresh()to restart the same timer without allocating a new one (see Timeout object). - Promise timers from
node:timers/promisesare cancelled with anAbortSignal, not with these functions.