Asynchronous JavaScript: Callbacks, the Event Loop, Tasks and Microtasks
The foundation of async JavaScript: why JavaScript is single-threaded yet non-blocking, callbacks for timers, events and Node's error-first APIs, callback hell, and the event loop explained: call stack, host APIs, task queue, microtask queue, rendering, and classic output-order puzzles.
kvi5hnuCode Sprout team member7 min readOn this page
Most programs spend much of their time waiting: for a click, a network response, a file, a timer. JavaScript runs your code on a single thread, so if it simply stopped and waited, the page would freeze and a server couldn't handle other requests. Instead, JavaScript is asynchronous: you start an operation, provide code to run when it finishes, and carry on. This article covers the oldest way to do that (callbacks) and the machinery that makes all of async JavaScript work: the event loop. Promises, async/await and async iteration in the following articles all build on it.
Interestingly, the core language has no I/O at all. Timers, network requests, file access and events are provided by the host environment (the browser or Node.js). JavaScript only defines how the results get back into your code.
Synchronous vs asynchronous
console.log("1. order placed");
setTimeout(() => console.log("3. confirmation email sent"), 0);
console.log("2. thank-you page shown");
1. order placed
2. thank-you page shown
3. confirmation email sent
setTimeout doesn't pause the program. It registers a callback and returns immediately; the callback runs later, after the current code has finished, even with a delay of 0.
Callbacks: the original async pattern
A callback is a function you pass to another function, to be called when something happens. You've already used them:
setTimeout(checkForUpdates, 60_000); // timers (article 89)
button.addEventListener("click", saveDraft); // browser events
fs.readFile("config.json", "utf8", (err, text) => { // Node file APIs
/* ... */
});
Node's error-first callbacks
Node's classic APIs use a convention: the callback's first argument is an error (or null on success), and the result comes after it. You must check the error every time:
function readConfig(name, callback) {
setTimeout(() => {
if (name.endsWith(".json")) callback(null, { name, port: 8080 });
else callback(new Error(`Unsupported file: ${name}`));
}, 10);
}
function handle(err, config) {
if (err) {
console.log("failed:", err.message);
return;
}
console.log("loaded", config);
}
readConfig("app.json", handle);
readConfig("app.yaml", handle);
console.log("reading...");
reading...
loaded { name: 'app.json', port: 8080 }
failed: Unsupported file: app.yaml
Node now offers promise versions of most APIs (node:fs/promises, node:timers/promises), and util.promisify converts error-first functions into promise-returning ones (article 95).
Why callbacks get painful
Callback hell
When each step depends on the previous one, callbacks nest deeper and deeper:
getUser(userId, (err, user) => {
if (err) return showError(err);
getOrders(user.id, (err, orders) => {
if (err) return showError(err);
getInvoice(orders[0].id, (err, invoice) => {
if (err) return showError(err);
sendEmail(user.email, invoice, (err) => {
if (err) return showError(err);
console.log("done");
});
});
});
});
The indentation (the "pyramid of doom") is the visible symptom. The deeper problems are:
-
Error handling is manual and repeated. Forget one
if (err)and errors vanish silently. -
try...catchdoesn't work across async boundaries. By the time a callback runs, the function that contained thetryhas already returned:javascripttry { setTimeout(() => { throw new Error("too late"); // not caught below: crashes the program }, 0); } catch (err) { console.log("never runs"); } -
Running steps in parallel and waiting for all of them needs hand-written counters.
-
Inversion of control. You hand your callback to someone else's code and trust it to call it exactly once, with the right arguments, at the right time. A buggy library might call it twice, never, or synchronously.
Don't call callbacks sometimes-sync, sometimes-async
An API that calls its callback synchronously in some cases and asynchronously in others makes the order of the caller's code unpredictable. This bug is nicknamed "releasing Zalgo":
const cache = new Map([[1, "Ana"]]);
function getUserInconsistent(id, callback) {
if (cache.has(id)) return callback(cache.get(id)); // sync!
setTimeout(() => callback("loaded " + id), 5); // async
}
function getUserConsistent(id, callback) {
if (cache.has(id)) return queueMicrotask(() => callback(cache.get(id))); // always async
setTimeout(() => callback("loaded " + id), 5);
}
let ready = false;
getUserInconsistent(1, () => console.log("inconsistent: ready is", ready));
getUserConsistent(1, () => console.log("consistent: ready is", ready));
ready = true;
inconsistent: ready is false
consistent: ready is true
Promises fix this by design: their callbacks are always asynchronous.
These problems are exactly what promises (articles 95 to 97) and async/await (article 98) were designed to solve. Callbacks remain perfect for events that happen many times (clicks, messages, stream chunks), where promises don't fit.
The event loop
How can single-threaded JavaScript wait for many things at once? It doesn't wait at all: the host does the waiting.

- The call stack. The engine runs your code one function call at a time. While anything is on the stack, nothing else in that thread can run. This is "run to completion".
- Host APIs.
setTimeout,fetch, file reads and event listeners hand work to the browser or Node, which handle it outside the JavaScript thread (in the OS, network stack or a thread pool). - Queues. When an operation finishes, the host queues its callback:
- the task queue (also called the macrotask or callback queue) for timers, I/O completions, UI events and messages;
- the microtask queue for promise reactions (
then,catch,finally, the code afterawait) andqueueMicrotaskcallbacks.
- The loop. Whenever the call stack is empty, the event loop:
- takes one task from the task queue and runs it to completion;
- runs all microtasks, including any queued while it's running, until the microtask queue is empty;
- lets the browser render (update layout and paint) if it's time to;
- repeats.
Browsers actually have several task queues (for user input, timers, networking) and pick between them by priority, and Node organizes its loop into phases (timers, I/O polling, setImmediate, close callbacks), but the rule that matters for your code is the same everywhere: a task runs to completion, then all microtasks run, before the next task.
The classic ordering puzzle
console.log("1 script start");
setTimeout(() => console.log("6 timeout"), 0);
Promise.resolve()
.then(() => console.log("3 microtask A"))
.then(() => console.log("5 microtask C"));
queueMicrotask(() => console.log("4 microtask B"));
console.log("2 script end");
setTimeout(() => {
console.log("7 timeout 2");
Promise.resolve().then(() => console.log("8 microtask inside timeout"));
}, 0);
setTimeout(() => console.log("9 timeout 3"), 0);
1 script start
2 script end
3 microtask A
4 microtask B
5 microtask C
6 timeout
7 timeout 2
8 microtask inside timeout
9 timeout 3
Step by step:
- The whole script is the first task: it logs 1 and 2, and queues three timers and two microtasks (A and B).
- The script ends, so the microtask queue drains: A runs, and its
thenqueues C; B runs; then C, because microtasks queued during draining also run before any task. - The first timer task runs (6). No microtasks are pending.
- The second timer task runs (7) and queues a microtask, which runs immediately after that task (8), before the third timer (9).
Consequences you should know
Long synchronous code freezes everything. While a loop runs for two seconds, no clicks are handled, no timers fire and the page can't repaint. Break heavy work into chunks (yielding with setTimeout or scheduler.yield()), or move it to a Web Worker.
Microtasks can starve tasks. Because the loop drains the microtask queue completely, a microtask that keeps queueing more microtasks blocks timers and rendering:
let count = 0;
function spin() {
if (++count < 100_000) queueMicrotask(spin);
else console.log("100,000 microtasks done");
}
setTimeout(() => console.log("timeout finally runs"), 0);
spin();
100,000 microtasks done
timeout finally runs
An endless microtask loop would hang the page completely, just like an infinite while loop.
State can change between tasks. Code in a callback sees the world as it is when the callback runs, not when it was registered.
Common questions
If JavaScript is single-threaded, how does fetch download in parallel?
The download happens in the browser's networking code, not in the JavaScript thread. JavaScript only starts the request and later runs your callback (or resolves your promise) when the response arrives.
What's the difference between a task and a microtask?
Tasks (timers, I/O, events) run one per loop iteration. Microtasks (promise reactions, queueMicrotask) run right after the current task finishes, all of them, before the next task or render.
Does setTimeout(fn, 0) run before Promise.resolve().then(fn)?
No. The promise reaction is a microtask and runs as soon as the current task finishes; the timer callback is a task, so it waits for the next loop iteration.
Is Node's event loop different from the browser's?
In the details, yes: Node has phases (timers, poll for I/O, check for setImmediate, close callbacks) and process.nextTick, which runs before promise microtasks. The core rule, one task then all microtasks, is the same.
Summary
- JavaScript runs on one thread; the host (browser or Node) performs waiting operations and queues callbacks when they finish.
- Callbacks are the oldest async pattern: timers, events and Node's error-first
(err, result)callbacks. - Nested callbacks make error handling, sequencing and parallelism hard,
try...catchcan't catch errors thrown later in callbacks, and APIs must never mix sync and async callbacks. - The event loop runs one task (script, timer, I/O, event) to completion, then all microtasks (promise reactions,
queueMicrotask), then renders, then the next task. - Long synchronous work and runaway microtasks block everything else.
Practice Questions
Predict the output:
setTimeout(() => console.log("T"), 0);
Promise.resolve().then(() => console.log("P"));
console.log("S");
Answer
S, P, T: synchronous code, then the microtask, then the timer task.
Why can't this function return the file's contents?
function load() {
let data;
fs.readFile("a.txt", "utf8", (e, t) => { data = t; });
return data;
}
Answer
readFile is asynchronous: the callback runs after load has already returned, so load returns undefined. Return a promise (or use async/await) or accept a callback instead.
A click handler runs a loop that takes 3 seconds. What does the user experience?
Answer
The page freezes for 3 seconds: no other events are handled, timers don't fire and nothing repaints until the handler returns, because the loop occupies the only JavaScript thread.
What's printed?
queueMicrotask(() => console.log("A"));
setTimeout(() => console.log("B"));
queueMicrotask(() => {
console.log("C");
queueMicrotask(() => console.log("D"));
});
Answer
A, C, D, B. All microtasks, including D queued during draining, run before the timer task.
Previous: JavaScript Iterator Helpers: map, filter, take, drop, flatMap and reduce on Any Iterator (ES2025)
Next: JavaScript Promises Explained: States, then, catch, finally and Creating Promises

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.