Timers and immediate callbacks
Local practice: Node.js 22.16.0 on Linux x64; proposed teaching baseline 26.13.1 remains untested. Copy only the listed files into a fresh disposable directory. No dependency installation or external services required. These are static Node.js examples, not verified ByteMind runner tasks.
Stop a repeating timer
let count = 0;const handle = setInterval(() => { console.log(++count); if (count === 3) clearInterval(handle);}, 5);Run:
node main.mjsExpected stdout:
123Exit status: 0. Expected stderr: empty.
How it works
setTimeout(callback, delay, ...args) and setInterval return Timeout handles; setImmediate returns an Immediate handle. Clear them with their corresponding clear functions. Delays are thresholds, not exact deadlines: other work may postpone execution. Inside an I/O callback, a newly scheduled immediate is expected before a newly scheduled timeout in the illustrated context. At top level their relative order is not a portable prediction. Promise timer APIs let you await a delay and support cancellation.
Schedule within a completed file read
import { readFile } from 'node:fs';readFile('item.txt', err => { if (err) throw err; setTimeout(() => console.log('timeout'), 0); setImmediate(() => console.log('immediate'));});Run:
node main.mjsExpected stdout:
immediatetimeoutExit status: 0. Expected stderr: empty.
Common mistake
An interval can keep a process alive and can launch overlapping asynchronous operations if the callback starts a promise without waiting. Use a bounded loop with an awaited delay when completion must precede the next operation.
Practice
Change the interval limit from three to two and confirm the process exits. Explain how to prevent overlapping asynchronous refresh operations.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Timers and immediate callbacks — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What does a 10 ms timeout specify?
How do you stop the repeating timer?
What can happen when an interval starts asynchronous work without awaiting it?