Timers: setTimeout, setInterval and their order

A timer is the oldest way to ask for code later: setTimeout runs a function once, setInterval runs it again and again, and both return a handle that cancels them. The delay is a floor, not a promise: it says when the callback becomes ready, and the event loop runs it when the stack is free.

This lesson shows the two functions, the order of two timers that were set with the same delay, an interval that stops itself, and what clearing a timer that has already fired does. Every program ends on its own, so the timers never keep the process alive by accident.

setTimeout and its handle

setTimeout(callback, delay) registers a task and returns a handle before the callback has run. The program below prints the lines around it, which shows the order the reader has to keep in mind: the registration is synchronous and the callback is not.

The file timeout.mjs:

console.log('before'); const timer = setTimeout(() => { console.log('the callback ran'); }, 10); console.log('after'); console.log('the handle is an object:', typeof timer);

node timeout.mjs

before
after
the handle is an object: object
the callback ran

The handle is a Timeout object, and the type is all a reader usually needs to know about it: it is the value that clearTimeout takes. The callback printed last because the two log lines were still on the stack, and the process stayed alive until the timer fired.

Two timers with one delay

Two timers with the same delay fire in the order they were registered, and a shorter delay overtakes a longer one. That is the whole ordering rule for timers, and it is why a callback that must run after another is registered after it rather than given a delay of its own.

The file order.mjs:

setTimeout(() => { console.log('the first timer'); }, 20); setTimeout(() => { console.log('the second timer'); }, 20); setTimeout(() => { console.log('the short timer'); }, 10); console.log('the synchronous line');

node order.mjs

the synchronous line
the short timer
the first timer
the second timer

The two timers of twenty milliseconds kept their registration order, and the ten millisecond one came before both. A delay of zero does not jump the queue either: it still makes a task, so every microtask runs first, as the lesson on the event loop showed.

setInterval and clearInterval

setInterval registers a callback that runs again after every delay until it is cleared. The handle is what clearInterval takes, and the callback below clears itself on the third run, which is the usual shape of a repeating job with a known end.

The file interval.mjs:

let ticks = 0; const timer = setInterval(() => { ticks += 1; console.log(`tick ${ticks}`); if (ticks === 3) { clearInterval(timer); console.log('the interval is cleared'); } }, 10);

node interval.mjs

tick 1
tick 2
tick 3
the interval is cleared

The program ended because the interval ended: an interval that is never cleared keeps the process alive for ever. The delay of an interval is counted from the end of the previous run, so a slow callback makes the ticks drift; a job that must not drift measures the time itself and sets a fresh timeout each round.

Clearing a timer

clearTimeout on a timer that has not fired removes it from the queue, and the callback never runs. On a timer that already fired it does nothing and throws nothing, which makes it safe to call in a cleanup path that does not know whether the timer was reached.

The file clear.mjs:

const cancelled = setTimeout(() => { console.log('this never prints'); }, 10); clearTimeout(cancelled); console.log('the timer was cancelled'); const fired = setTimeout(() => { console.log('this one printed'); clearTimeout(fired); console.log('clearing it again changes nothing'); }, 10);

node clear.mjs

the timer was cancelled
this one printed
clearing it again changes nothing

The first callback never ran, and the second called clearTimeout from inside itself without an error. The next lesson replaces the callback with a promise, which is the value that a timer usually returns once a program has more than one thing to wait for.

Exercises

  1. Set two timers with delays of 30 and 10 milliseconds, the longer one first, and print the order.
  2. Clear the second timer before it fires. Which line of the program is missing from the output?
  3. Make the interval print five times instead of three. How many lines does the program print in total?
  4. Call clearTimeout with no argument. What does the program do?
  5. Start an interval and clear it from a second timer after two runs. Which callback runs last?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does setTimeout return?

    Answer

    A handle that clearTimeout takes

    The handle is a Timeout object, and it is the only way to cancel the timer.

  2. When does a timer callback run?

    Answer

    After the delay, when the loop takes the task

    The delay says when the task becomes ready; the loop runs it when the stack is free.

  3. Two timers are registered with the same delay. What decides their order?

    Answer

    The order they were registered in

    Timers that are ready at the same moment keep the order of registration.

  4. What does clearInterval do?

    Answer

    Stops the repeats of that interval

    The handle names the interval, and clearing it removes the next run from the queue.

  5. What does this program print? const timer = setTimeout(() => console.log("late"), 10); clearTimeout(timer); console.log("now");

    Answer

    now

    The timer was cancelled before it fired, so only the synchronous line printed.

  6. What does this program print? setTimeout(() => console.log("first"), 20); setTimeout(() => console.log("second"), 10);

    Answer

    second / first

    The shorter delay is ready first, and the loop takes it first.

  7. What does this program print? let n = 0; const timer = setInterval(() => { n += 1; console.log(n); if (n === 2) clearInterval(timer); }, 10);

    Answer

    1 / 2

    The second run clears the interval, so no third run is queued.

  8. Does setTimeout(callback, 0) run before a promise callback that is already queued?

    Answer

    No, the microtask runs first

    A timer makes a task, and every microtask runs before the next task.

  9. What keeps the process alive while a timer is pending?

    Answer

    The timer itself, until it fires or is cleared

    A pending timer is an active handle, and the runtime waits for it.

  10. What does clearTimeout do on a timer that already fired?

    Answer

    Nothing, and it throws nothing

    The handle is no longer in the queue, and clearing it is a no-op.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev