Sub topic 4
Asynchronous Callbacks: setTimeout and I/O
This chapter assumes you can write functions and arrow functions, run a script with Node.js, and pass a callback to a function such as Array.prototype.map. The earlier chapters covered synchronous callbacks, which run before the function that receives them returns. Here you will meet callbacks that run later, after the code that registered them has finished.
What Makes a Callback Asynchronous
A callback is asynchronous when the function you hand it to returns before the callback runs. The receiving function stores the callback, starts some work outside your JavaScript code (a timer, a file read, a network request), and returns right away. When that work finishes, the runtime calls your callback.
Compare the two kinds:
| Property | Synchronous callback | Asynchronous callback |
|---|---|---|
| When it runs | During the call that received it | After that call has returned and the current script has finished |
| Examples | `map`, `filter`, `forEach`, `sort` | `setTimeout`, `fs.readFile`, `addEventListener` |
| Return value useful to the caller? | Yes, often (`map` collects them) | No, the caller is already gone |
| `try/catch` around the call catches its errors? | Yes | No |
| Blocks other code while waiting? | Yes | No |
JavaScript runs your code on a single thread. If a file read made that thread wait, nothing else could happen: no timers, no clicks, no other requests. Asynchronous callbacks solve this. The slow work happens elsewhere (in the operating system, or in a thread pool inside Node.js), and JavaScript only gets involved again when there is a result to handle.
setTimeout: The Simplest Asynchronous Callback
setTimeout(callback, delay) asks the runtime to call callback after at least delay milliseconds. It returns at once.
console.log('A');
setTimeout(() => console.log('C'), 0);
console.log('B');
// Output: A, B, CThe delay is 0, but C still prints last. setTimeout never calls its callback during the current run of your code. It hands the callback to the timer system. When the timer expires, the callback waits in a task queue until the call stack is empty. Only then does it run. The script must finish printing B first.
The next chapter covers how the event loop picks callbacks off the queues. For now, remember one rule: an asynchronous callback never interrupts running code. It always waits for the current synchronous work to finish.
The delay is a minimum, not a promise
The delay tells the runtime the earliest time the callback may run. If the thread is busy, the callback runs late:
const start = Date.now();
setTimeout(() => {
console.log('Timer fired after', Date.now() - start, 'ms');
}, 100);
// Busy-wait for 500 ms, blocking the only thread
while (Date.now() - start < 500) {}
console.log('Loop done after', Date.now() - start, 'ms');
// Loop done after 500 ms
// Timer fired after ~500 ms (not 100)The timer expired at 100 ms, but its callback could not run until the loop released the thread. Browsers also clamp delays: nested timers (a timer scheduled from a timer, more than five levels deep) get a minimum of about 4 ms, and background tabs may be throttled to 1000 ms or more. Never use setTimeout for precise timing.
Passing arguments and cancelling
setTimeout accepts extra arguments and forwards them to the callback. It returns an identifier you can pass to clearTimeout to cancel the callback before it runs.
function greet(name, punctuation) {
console.log('Hello, ' + name + punctuation);
}
const id = setTimeout(greet, 1000, 'Ada', '!');
const other = setTimeout(greet, 1000, 'Bob', '?');
clearTimeout(other); // Bob is never greeted
// After one second: Hello, Ada!Notice that greet is passed without parentheses. Writing setTimeout(greet('Ada', '!'), 1000) calls greet immediately and passes its return value (undefined) as the callback. This mistake is common, and it fails silently in browsers. Node.js throws a TypeError because the callback is not a function.
setInterval: a callback that repeats
setInterval(callback, delay) calls the callback repeatedly, about every delay milliseconds, until you call clearInterval.
let ticks = 0;
const intervalId = setInterval(() => {
ticks++;
console.log('tick', ticks);
if (ticks === 3) {
clearInterval(intervalId);
console.log('stopped');
}
}, 200);
// tick 1, tick 2, tick 3, stoppedIf you forget clearInterval, the callback runs forever. In Node.js, an active interval also keeps the process from exiting.
I/O Callbacks: Reading a File
Timers are the simplest case. The more important use of asynchronous callbacks is I/O (input/output): reading files, querying databases, making HTTP requests. Node.js core APIs pass a callback that receives the result when the operation finishes.
The following script writes a file and then reads it back, so it runs as shown:
const fs = require('node:fs');
fs.writeFileSync('message.txt', 'Hello from disk');
console.log('1: before readFile');
fs.readFile('message.txt', 'utf8', (err, data) => {
if (err) {
console.error('Read failed:', err.message);
return;
}
console.log('3: file contents:', data);
});
console.log('2: after readFile');
// 1: before readFile
// 2: after readFile
// 3: file contents: Hello from diskfs.readFile starts the read and returns immediately, so line 2 prints before the contents arrive. The callback's first parameter, err, follows Node's error-first convention, which a later chapter covers in detail. For now, check err before you use data.
fs.readFileSync would read the same file synchronously. That is fine in a short script or at startup. In a server it is a problem, because every request waits while the thread is blocked on disk.
Mistake 1: Trying to Return a Value from an Asynchronous Callback
This is the most common error with asynchronous callbacks:
const fs = require('node:fs');
fs.writeFileSync('message.txt', 'Hello from disk');
function readMessage() {
let result;
fs.readFile('message.txt', 'utf8', (err, data) => {
result = data; // runs later
});
return result; // runs now
}
console.log(readMessage()); // undefinedreturn result runs before the callback assigns anything. The return data statement inside the callback would not help either, because it returns to whoever called the callback (Node's internals), not to readMessage's caller.
The fix is to pass the result forward instead of back. The function accepts its own callback and calls it when the data is ready:
const fs = require('node:fs');
fs.writeFileSync('message.txt', 'Hello from disk');
function readMessage(callback) {
fs.readFile('message.txt', 'utf8', (err, data) => {
if (err) return callback(err);
callback(null, data.toUpperCase());
});
}
readMessage((err, message) => {
if (err) {
console.error(err.message);
return;
}
console.log(message); // HELLO FROM DISK
});The pattern spreads upward: once a function depends on an asynchronous result, its callers must also accept a callback (or, as later chapters show, return a Promise).
Mistake 2: Expecting try/catch to Catch Errors in the Callback
A try/catch only catches errors thrown while its try block is on the call stack. An asynchronous callback runs after that block has finished.
try {
setTimeout(() => {
throw new Error('boom');
}, 0);
} catch (err) {
console.log('Caught:', err.message); // never runs
}
console.log('try/catch finished');
// try/catch finished
// Uncaught Error: boom (Node.js exits with this error)The try block only registered the timer. When the callback throws, nothing above it on the stack is waiting to catch the error. In Node.js the process crashes with an uncaught exception. In a browser, the error is logged and the page keeps running.
Put error handling inside the callback, where the error happens:
setTimeout(() => {
try {
throw new Error('boom');
} catch (err) {
console.log('Caught inside callback:', err.message);
}
}, 0);This is why I/O APIs report failures through a callback argument (err) instead of throwing. Throwing has nowhere useful to go.
Mistake 3: Assuming Order Between Independent Operations
Two asynchronous operations started one after the other can finish in either order. Timers with different delays have a predictable order. I/O operations do not.
const fs = require('node:fs');
fs.writeFileSync('small.txt', 'x');
fs.writeFileSync('large.txt', 'x'.repeat(5_000_000));
fs.readFile('large.txt', 'utf8', () => console.log('large done'));
fs.readFile('small.txt', 'utf8', () => console.log('small done'));
// Usually: small done, large done
// The order is not guaranteedIf step B needs step A's result, start B inside A's callback:
const fs = require('node:fs');
fs.writeFileSync('first.txt', 'one');
fs.writeFileSync('second.txt', 'two');
fs.readFile('first.txt', 'utf8', (err, first) => {
if (err) return console.error(err.message);
fs.readFile('second.txt', 'utf8', (err2, second) => {
if (err2) return console.error(err2.message);
console.log(first, second); // one two
});
});This nesting works, but it grows to the right with each step. The chapter on callback hell shows how to flatten it.
If operations are independent and you need all their results, start them all at once and count completions:
const fs = require('node:fs');
const files = ['a.txt', 'b.txt', 'c.txt'];
files.forEach((name, i) => fs.writeFileSync(name, 'file ' + i));
const results = [];
let remaining = files.length;
files.forEach((name, index) => {
fs.readFile(name, 'utf8', (err, data) => {
if (err) return console.error(err.message);
results[index] = data; // store by index, not by finish order
remaining--;
if (remaining === 0) {
console.log(results); // [ 'file 0', 'file 1', 'file 2' ]
}
});
});Storing by index keeps the results in request order, whatever order the reads finish in.
Summary of the Working Model
- Calling an asynchronous API registers your callback and returns immediately.
- The slow work happens outside your JavaScript code.
- When the work finishes, the callback is queued.
- The callback runs only after all currently running synchronous code has finished.
- Results and errors arrive as callback arguments. Return values and outer
try/catchblocks cannot reach them.
Exercise
Predict the output order of this script and explain why. console.log('start'); setTimeout(() => console.log('timer 50'), 50); setTimeout(() => console.log('timer 0'), 0); for (let i = 0; i < 1e8; i++) {} console.log('end');
Show answer
The output is start, end, timer 0, timer 50. Both setTimeout calls return immediately, so the loop and the 'end' log run first, as synchronous code. Even if the loop takes longer than 50 ms, neither callback can interrupt it. Once the stack is empty, the timers run in expiry order: the 0 ms timer expired first, so 'timer 0' prints before 'timer 50'.
Exercise
This function is meant to return the length of a file's contents, but it always logs undefined. Rewrite it so the caller receives the length. const fs = require('node:fs'); function fileLength(path) { let len; fs.readFile(path, 'utf8', (err, data) => { len = data.length; }); return len; } console.log(fileLength('message.txt'));
Show answer
fs.readFile returns before its callback runs, so len is still undefined at the return statement. Accept a callback and pass the result into it: function fileLength(path, callback) { fs.readFile(path, 'utf8', (err, data) => { if (err) return callback(err); callback(null, data.length); }); } fileLength('message.txt', (err, len) => { if (err) return console.error(err.message); console.log(len); });
Exercise
Why does wrapping setTimeout(() => { throw new Error('x'); }, 0) in try/catch fail to catch the error, and where should the try/catch go?
Show answer
The try block only registers the timer and then finishes. The callback runs later, on a fresh call stack that has no enclosing try/catch, so the error is uncaught. Put the try/catch inside the callback, around the code that might throw.