Timer delays and cancellation
How it works
setTimeout(callback, delay) requests a later host callback and returns a host-specific handle. The delay is not an appointment or a guaranteed execution time: the host may clamp it and a busy loop may postpone it. clearTimeout(handle) prevents a pending timer callback if it has not already begun. Repeating timers also need cleanup. Prefer measuring actual elapsed time rather than counting ticks when accuracy matters.
Example 1
const handle = setTimeout(() => console.log("unexpected"), 0);clearTimeout(handle);setTimeout(() => console.log("kept"), 0);Expected output in the tested environment:
keptThe canceled pending callback does not run.
Example 2
Expected output in the tested environment:
nowlaterZero delay still requests a later callback.
Common mistake
Do not compare browser numeric timer IDs with Node timer objects as if their representations were portable.
Practice
Create a repeating timer that stops after three callbacks using clearInterval; do not assert an exact elapsed time.
Run this practice in the documented local environment. ByteMind module and asynchronous grader support is not yet verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Timer delays and cancellation — Knowledge Check
Reason about the concept and predict its behavior in the indicated environment.
Does setTimeout(fn, 0) execute fn synchronously?
What does clearTimeout need to cancel a pending timer?
Why should elapsed time not be computed merely as tick count times requested interval?
For Timer delays and cancellation, what is the console output of example 1 in Node.js 22.16.0?
const handle = setTimeout(() => console.log("unexpected"), 0);clearTimeout(handle);setTimeout(() => console.log("kept"), 0);For Timer delays and cancellation, what is the console output of example 2 in Node.js 22.16.0?
setTimeout(() => console.log("later"), 0);console.log("now");