On this page

Cancelling timers

History

The setImmediate(), setInterval(), and setTimeout() methods each return objects that represent the scheduled timers. These can be used to cancel the timer and prevent it from triggering.

For the promisified variants of setImmediate() and setTimeout(), an AbortController may be used to cancel the timer. When canceled, the returned Promises will be rejected with an 'AbortError'.

For setImmediate():

import { setImmediate as setImmediatePromise } from 'node:timers/promises';

const ac = new AbortController();
const signal = ac.signal;

// We do not `await` the promise so `ac.abort()` is called concurrently.
setImmediatePromise('foobar', { signal })
  .then(console.log)
  .catch((err) => {
    if (err.name === 'AbortError')
      console.error('The immediate was aborted');
  });

ac.abort();
const { setImmediate: setImmediatePromise } = require('node:timers/promises');

const ac = new AbortController();
const signal = ac.signal;

setImmediatePromise('foobar', { signal })
  .then(console.log)
  .catch((err) => {
    if (err.name === 'AbortError')
      console.error('The immediate was aborted');
  });

ac.abort();

For setTimeout():

import { setTimeout as setTimeoutPromise } from 'node:timers/promises';

const ac = new AbortController();
const signal = ac.signal;

// We do not `await` the promise so `ac.abort()` is called concurrently.
setTimeoutPromise(1000, 'foobar', { signal })
  .then(console.log)
  .catch((err) => {
    if (err.name === 'AbortError')
      console.error('The timeout was aborted');
  });

ac.abort();
const { setTimeout: setTimeoutPromise } = require('node:timers/promises');

const ac = new AbortController();
const signal = ac.signal;

setTimeoutPromise(1000, 'foobar', { signal })
  .then(console.log)
  .catch((err) => {
    if (err.name === 'AbortError')
      console.error('The timeout was aborted');
  });

ac.abort();
M

clearImmediate

History
clearImmediate(immediate): void
Attributes
immediate:Immediate
An Immediate object as returned by setImmediate().

Cancels an Immediate object created by setImmediate().

M

clearInterval

History
clearInterval(timeout): void
Attributes
timeout:Timeout | string | number
A Timeout object as returned by setInterval() or the primitive of the Timeout object as a string or a number.

Cancels a Timeout object created by setInterval().

M

clearTimeout

History
clearTimeout(timeout): void
Attributes
timeout:Timeout | string | number
A Timeout object as returned by setTimeout() or the primitive of the Timeout object as a string or a number.

Cancels a Timeout object created by setTimeout().