The Event Loop Explained: Tasks, Microtasks and Rendering
A complete guide to the JavaScript event loop in browsers and Node.js 24: tasks, microtasks, rendering, libuv phases, nextTick, starvation and measurement.

Every JavaScript developer eventually meets a piece of code whose output order makes no sense. A zero-delay timer runs after a promise that was created later. An await seems to take two turns instead of one. A page freezes although nothing in the code looks slow. A server stops answering requests for two seconds while a single function runs. All of these are the same thing seen from different angles, and the thing is the event loop: the mechanism that decides what your single thread does next. This guide explains it from the ground up, in the browser and in Node.js 24, with enough precision that you can predict the order of any asynchronous program on paper. It starts with the model, moves through tasks, microtasks and rendering, walks through the phases of the Node.js loop, works a set of ordering puzzles with their answers, shows how loops get blocked and starved, and finishes with measurement and debugging. Every example prints the output it produces, so you can check your own predictions against it.
A word on honesty about the subject: the event loop is specified in two places that do not agree in every detail. The HTML Standard defines the browser's loop, and Node.js documents its own, built on a C library named libuv. They share the central rules, a task at a time and microtasks between tasks, and differ in the surrounding machinery. Where the difference matters, the text says which loop it means.
Why there is an event loop at all
JavaScript runs your code on one thread with one call stack. A function that is running cannot be interrupted by another function, and two pieces of your code never run at the same instant. This design removes a whole class of problems, since you never need a lock to protect a variable from another thread of your own code, and it creates a different problem: if a function takes a long time, everything waits for it. A click cannot be handled, a timer cannot fire and a network response cannot be read until the function returns.
The environment solves that by never asking your code to wait. When you start an operation that takes time, such as a timer, a network request or a file read, the environment does the waiting outside your thread, using operating system facilities, and registers a callback. When the operation completes, the environment puts a task in a queue. Your thread's only job between tasks is to ask "is there another one?". The loop is that question asked forever: take the next task, run it to the end, take the next.
console.log("A: running");
setTimeout(() => console.log("C: the timer's task"), 0);
console.log("B: still running the same task");A: running
B: still running the same task
C: the timer's taskThe whole script is one task. Both console.log lines belong to it, and the timer's callback becomes a separate task that cannot start until the script's task ends. Run-to-completion is the guarantee that makes JavaScript predictable: once a task starts, nothing else in your program runs until it finishes.
The four parts of the model
Four pieces are enough to explain nearly everything.
The call stack holds the functions that are executing right now. Calling a function pushes a frame, and returning pops it. When the stack is empty, the current task is over.
The task queues hold callbacks that are ready to run: timer callbacks, input and output callbacks, user input events, messages from other windows and workers. A browser keeps several queues for different task sources and may favor some over others, for example giving user input a higher priority than timers. For reasoning about your own code, you can treat them as one ordered queue per source, with the oldest ready task taken first.
The microtask queue holds short jobs that must run as soon as the current task's stack empties, before the loop moves on. Promise reactions, the continuation of an async function after await, callbacks from queueMicrotask and MutationObserver callbacks live here.
The rendering step, in a browser only, is where the engine recalculates styles, lays out the page and paints, when a frame is due.
The loop's body can be written in a few lines, and the rest of this guide is footnotes to it.
loop forever:
pick the oldest ready task from a task queue and run it to completion
run every microtask, including ones queued while running microtasks, until none remain
if this is a browser and a frame is due:
run animation frame callbacks, then style, layout, paintThat pseudocode is accurate for the browser at the level of detail most programs need. The real algorithm has more conditions, such as skipping rendering when nothing has changed and the display is not ready, and the pseudocode ignores them on purpose.
Tasks: what creates them
A task is one unit of work that the loop takes from a queue. The script that your page loads is a task, and so is each of the following once its time comes.
| Source | Example |
|---|---|
| Timers | The callback of setTimeout or setInterval |
| Input events | A click, keypress or scroll event handler |
| Network | A response arriving, delivered to fetch or XMLHttpRequest |
| Messages | postMessage, MessageChannel, BroadcastChannel, worker messages |
| Navigation and history | Page loads and popstate |
| Node.js I/O | The callback of a finished file read, a socket event, a child process event |
| Node.js immediates | The callback of setImmediate |
Two properties of tasks cause most of the confusion. First, the loop runs one task at a time, so a task that runs for 300 ms delays every task behind it by 300 ms, including a click the user made while it ran. Second, tasks are ordered by when they became ready, and not by when you asked for them. A timer set for 100 ms that is ready before a timer set for 50 ms that was created later would run first, though that situation is unusual in practice.
setTimeout(() => console.log("timer 50"), 50);
setTimeout(() => console.log("timer 10"), 10);
setTimeout(() => console.log("timer 0"), 0);
console.log("script");script
timer 0
timer 10
timer 50The timers ran in the order of their delays and not in the order they were written. A timer is ready when its delay has elapsed, and the loop takes the earliest ready one. If the script had blocked for 100 ms, all three would be ready at once, and they would run in order of their due times, which here is the same order.
Microtasks: the queue that jumps the line
The microtask queue exists so that small follow-up work can run right after the code that caused it, before the loop gets to anything else. Promises are the main reason. When a promise settles, its handlers do not run immediately, because that would run your code in the middle of someone else's function. They are queued as microtasks, which run when the stack is empty, and still before the next task.
The rule is precise: after a task completes, and whenever the stack empties in the middle of a task, the engine performs a microtask checkpoint. It takes the oldest microtask, runs it, and repeats until the queue is empty, including microtasks added by the ones it ran.
setTimeout(() => console.log("task: timeout"), 0);
Promise.resolve().then(() => {
console.log("microtask 1");
queueMicrotask(() => console.log("microtask 3, queued by microtask 1"));
});
Promise.resolve().then(() => console.log("microtask 2"));
console.log("script");script
microtask 1
microtask 2
microtask 3, queued by microtask 1
task: timeoutMicrotask 3 was added while microtask 1 ran, and it went to the back of the microtask queue, behind microtask 2, and in front of every task. Everything in the microtask queue finishes before the timer's task begins, however many there are.
await participates in this. When an async function reaches await, its continuation is scheduled as a microtask once the awaited promise settles. That is why await always yields, even for a value that is already available, and why two async functions that alternate through await interleave one step at a time, as the post on how await works shows.
async function worker(name) {
console.log(name, "step 1");
await null;
console.log(name, "step 2");
await null;
console.log(name, "step 3");
}
worker("A");
worker("B");
console.log("main done");A step 1
B step 1
main done
A step 2
B step 2
A step 3
B step 3Each function ran to its first await, the main script finished and then the two took turns, one microtask each. The order of the interleaving is an observable detail of the specification, and worth knowing when you debug logs from concurrent code, though no program should depend on it.
Starvation: when microtasks never end
Because the microtask queue must be empty before the loop continues, a microtask that always queues another one runs forever and nothing else gets a turn. Timers do not fire, input is ignored and in a browser the page never repaints.
let remaining = 100000;
function spin() {
if (--remaining > 0) queueMicrotask(spin);
}
setTimeout(() => console.log("timer ran, remaining:", remaining), 0);
queueMicrotask(spin);timer ran, remaining: 0The bound makes the program finish. The timer saw remaining at zero, so all hundred thousand microtasks ran before it. Remove the bound, and the timer never fires. A recursive promise chain behaves the same way, such as function poll() { return Promise.resolve().then(poll); }, and so does an async function with a loop that awaits something already resolved. When code needs to wait for the rest of the world, it has to go through a task, with a timer or setImmediate, because only a task boundary lets timers and input in. The post on microtasks versus macrotasks develops the idea further.
The browser's rendering step
In a browser, the loop has one more job. After a task and its microtasks, if a frame is due, the browser updates the rendering. The HTML Standard's "update the rendering" algorithm runs, in order, several things that matter to you: it runs requestAnimationFrame callbacks, it recalculates styles, it performs layout, it runs resize and intersection observers and then it paints.
A frame is due when the display is ready for one, about every 16.7 ms on a 60 Hz screen and 8.3 ms on a 120 Hz screen, and the browser may skip an update if nothing changed or the tab is hidden. Rendering takes the same thread as your JavaScript, so a long task also delays painting, which is why a frozen script produces a frozen page.
const box = document.querySelector("#box");
box.style.width = "100px";
box.style.width = "200px";
box.style.width = "300px";
console.log("three style changes, no paint yet");three style changes, no paint yetThe three assignments change the style within one task, and the browser paints once, after the task, with the final width. Intermediate states are never shown, because painting happens only at the rendering step. This is also why a JavaScript loop that changes the DOM a thousand times does not produce a thousand frames.
requestAnimationFrame(callback) schedules a callback for the start of the next rendering step, before style and layout, which is the right moment to make visual changes. The post on requestAnimationFrame shows how to write a loop that does not depend on the refresh rate.
console.log("script");
requestAnimationFrame(() => console.log("animation frame callback"));
setTimeout(() => console.log("timeout 0"), 0);
Promise.resolve().then(() => console.log("microtask"));script
microtask
timeout 0
animation frame callbackThe order of the last two lines is not fixed by the specification. The timer's task and the rendering step compete, and a browser may paint before a zero-delay timer runs, or after. The microtask is always first, and the animation frame callback runs at the rendering step, at the next frame the browser chooses to produce.
Layout is the expensive part of the step, and a script can force it early by reading a layout property, such as offsetHeight or getBoundingClientRect(), after changing a style. The browser then computes layout immediately instead of waiting for the rendering step. Alternating writes and reads in a loop forces a layout on every iteration, a problem named layout thrashing. Batch reads before writes to avoid it.
Long tasks and responsiveness
A task that runs for more than 50 ms is called a long task, and while it runs the page cannot respond. The browser measures the consequence as the delay between an input event and the next paint, which the Interaction to Next Paint metric reports. The only remedy is to make tasks shorter, by splitting work into slices and returning to the loop between them so that input and rendering can run.
Not every way of "waiting" returns to the loop, and the difference matters. Awaiting a promise yields to other microtasks and not to tasks, so it does not let input or rendering run. A macrotask boundary does: setTimeout, a MessageChannel message or scheduler.yield().
async function chunked(items, work) {
for (let i = 0; i < items.length; i++) {
work(items[i]);
if (i % 100 === 99) {
await new Promise((resolve) => setTimeout(resolve, 0));
}
}
}
await chunked(Array.from({ length: 250 }, (_, i) => i), () => {});
console.log("processed in slices of 100");processed in slices of 100Between each slice, the loop could run any pending input or rendering. In a modern browser, await scheduler.yield() does the same with a better guarantee, since the continuation resumes ahead of other queued tasks, as described in the post on scheduler.yield. For work that is not urgent, [requestIdleCallback and scheduler.postTask](/library/requestidlecallback-scheduler-posttask) let the browser order it behind everything that matters more.
When a single operation cannot be sliced, such as parsing a very large JSON document or compressing a buffer, the answer is a worker thread. A worker has its own event loop on its own thread, and the main thread's loop is not involved while it computes. The messages that come back are ordinary tasks.
The Node.js event loop
Node.js uses V8 for JavaScript and libuv for the loop, and libuv organizes the loop into phases. Each iteration passes through them in a fixed order, and each phase has its own queue of callbacks. The microtask queue and the process.nextTick queue are drained between callbacks, not in a phase of their own.
| Phase | What runs |
|---|---|
| timers | Callbacks of setTimeout and setInterval whose time has come |
| pending callbacks | Some system-level callbacks deferred from the previous iteration |
| idle, prepare | Internal use |
| poll | Retrieves new I/O events and runs their callbacks; may wait here for events |
| check | Callbacks scheduled by setImmediate |
| close callbacks | For example the close event of a socket |
The poll phase is the heart of it. If there are callbacks scheduled for the check phase, the loop does not wait in poll and moves on. If there are none, it blocks in poll until an I/O event arrives or until the next timer is due, which is how an idle Node.js process uses no processor time.
The consequence for ordering is that setImmediate runs right after the poll phase, while a timer runs at the start of the next iteration. Inside an I/O callback, the loop is in the poll phase, so setImmediate always comes before a zero-delay timer.
import { readFile } from "node:fs";
readFile("package.json", () => {
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
});immediate
timeoutThe script assumes a package.json in the working directory. From the main module, in contrast, the order of setTimeout(fn, 0) and setImmediate(fn) is not deterministic, because it depends on whether a millisecond has elapsed by the time the loop first reaches the timers phase. Do not write code that depends on it. The post on queueMicrotask, setTimeout and setImmediate compares the three in detail.
process.nextTick
Node.js has one more queue. Callbacks scheduled with process.nextTick run after the current operation finishes, before the loop continues and before promise microtasks. It predates promises and still appears all over the standard library. In a CommonJS script, the order is: synchronous code, then nextTick callbacks, then promise microtasks, then tasks. In the main body of an ES module, the module is itself evaluated inside a promise job, so promise microtasks run before nextTick callbacks, which reverses the order for the same code.
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");sync
nextTick
promise
timeout
immediateThis is the CommonJS result, with the last two lines in either order from the main module. New code should prefer queueMicrotask, which behaves the same in browsers, and the post on process.nextTick versus queueMicrotask explains when each is the right choice. Both queues can starve the loop in the way described earlier, and nextTick can starve even promise callbacks, since it is drained first.
Microtasks run between callbacks
Since Node.js 11, the microtask queue is drained after each individual callback in the timers and check phases, matching the browser. In older versions, it was drained only after the whole phase, so two timers that were due together ran back to back before any promise callback. If you read an older write-up that shows a different order, that is why.
setTimeout(() => {
console.log("timer 1");
Promise.resolve().then(() => console.log("promise inside timer 1"));
}, 0);
setTimeout(() => console.log("timer 2"), 0);timer 1
promise inside timer 1
timer 2The thread pool
Not everything in Node.js is done by the event loop's thread. libuv keeps a pool of worker threads, four by default and configurable with UV_THREADPOOL_SIZE, for operations that have no non-blocking system call: file system operations, DNS lookups made with dns.lookup, and some crypto and zlib functions. When you call fs.readFile or crypto.pbkdf2, the work runs on a pool thread, and when it finishes, a callback is queued for the loop. This is why a CPU-heavy crypto call can use several cores without any worker code on your side, and why many simultaneous file operations queue up behind the four threads. Network sockets do not use the pool, since the operating system provides non-blocking interfaces for them.
Working through ordering puzzles
The best way to make the model stick is to apply it. Each puzzle gives code and asks for the output. Work it out before reading the answer, using three rules: run the synchronous code first, drain all microtasks, then take one task and repeat.
Puzzle 1: a promise and a timer.
setTimeout(() => console.log("1"), 0);
Promise.resolve().then(() => console.log("2"));
console.log("3");3
2
1Synchronous code prints 3. The microtask checkpoint prints 2. The timer's task prints 1.
Puzzle 2: async functions.
async function a() {
console.log("a1");
await b();
console.log("a2");
}
async function b() {
console.log("b");
}
console.log("start");
a();
console.log("end");start
a1
b
end
a2a() runs synchronously up to its await, which includes calling b(), which prints b and returns a resolved promise. The await suspends a, and the script continues to print end. The continuation, a2, runs as a microtask afterwards.
Puzzle 3: then versus await.
Promise.resolve().then(() => console.log("then 1")).then(() => console.log("then 2"));
(async () => {
await null;
console.log("await 1");
await null;
console.log("await 2");
})();then 1
await 1
then 2
await 2Both started a microtask in the same checkpoint, in source order: the first then handler and the continuation of the async function. Each continuation queues the next one at the back of the queue, so the two sequences alternate.
Puzzle 4: a nested timer.
setTimeout(() => {
console.log("outer");
setTimeout(() => console.log("inner timer"), 0);
Promise.resolve().then(() => console.log("inner microtask"));
}, 0);
setTimeout(() => console.log("second outer"), 0);outer
inner microtask
second outer
inner timerAfter the first timer's callback, its microtask runs before the next task. The second outer timer was already due, so it goes before the inner timer, which was created later and is due later.
Puzzle 5: a thenable.
const thenable = {
then(resolve) {
console.log("then called");
resolve("value");
},
};
Promise.resolve(thenable).then((value) => console.log(value));
console.log("sync");sync
then called
valueAdopting a thenable takes an extra microtask, in which the engine calls its then method, so then called is printed after the synchronous line. Native promises avoid that extra step, which is part of why thenables are slower to await.
Blocking the loop
The loop can only do one thing at a time, so anything that runs for a long time on the main thread stops everything else. In a server, that means no requests are answered. The usual causes are not the obvious ones.
A synchronous API with Sync in its name, such as readFileSync, execSync or pbkdf2Sync, holds the thread for the duration of the call. These are fine at startup and in command line tools, and a defect in a request handler.
Heavy computation without any I/O blocks just as well: sorting a very large array, a large JSON.parse or JSON.stringify, building a big string, a tight loop over millions of items. Marking the function async changes nothing, since the computation runs on the caller's stack.
async function heavy() {
let total = 0;
for (let i = 0; i < 30_000_000; i++) total += i;
return total;
}
setTimeout(() => console.log("timer"), 0);
const promise = heavy();
console.log("heavy returned a promise");
console.log(await promise);heavy returned a promise
449999985000000
timerThe loop ran inside the call, before heavy returned its promise, so even the zero-delay timer waited for all of it.
A third cause is pathological regular expressions. A pattern with nested quantifiers, run against an input that almost matches, can take exponential time, and a single request can stall a server. The remedy is to avoid ambiguous patterns, to limit input length and, where untrusted input meets a complex pattern, to use a linear-time engine or run the match in a worker.
The remedies share a shape. Move the work off the thread, with a worker or a child process, or slice it with task boundaries so the loop breathes between pieces, or replace the synchronous call with its asynchronous version so the waiting happens outside. The post on what blocks and what does not lists the common offenders.
Measuring the loop
You cannot fix what you cannot see, and the loop's health has a simple measure: how late is it running? In Node.js, monitorEventLoopDelay from node:perf_hooks samples the delay between when a timer should fire and when it does, and reports a histogram.
import { monitorEventLoopDelay } from "node:perf_hooks";
const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();
const start = Date.now();
while (Date.now() - start < 100) {
// block for 100 ms
}
await new Promise((resolve) => setTimeout(resolve, 40));
histogram.disable();
console.log("max delay over 50 ms:", histogram.max / 1e6 > 50);
console.log("samples recorded:", histogram.count > 0);max delay over 50 ms: true
samples recorded: trueThe histogram's values are in nanoseconds, so dividing by a million gives milliseconds. In production, export the 99th percentile as a metric and alert when it rises. A rising event loop delay is the earliest and clearest sign that something is blocking, and it appears before request latency does.
performance.eventLoopUtilization() reports the fraction of time the loop was busy instead of idle, which tells you how close the process is to saturation. A process whose loop is 90 percent utilized has little room left for a spike. In browsers, the Long Tasks API reports tasks longer than 50 ms through a PerformanceObserver, and the Performance panel in developer tools draws each task as a block on the main thread, so you can see which function owns the time.
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log("long task:", Math.round(entry.duration), "ms");
}
});
observer.observe({ entryTypes: ["longtask"] });long task: 187 msThe duration shown is an example of what the observer would report in a page with a long task. The numbers will be yours.
What the loop does not do
Several beliefs about the loop are common and wrong. Knowing them saves time.
The loop does not run your code in parallel. Callbacks run one at a time, and only the waiting happens elsewhere. It does not make async functions run on another thread, since an async function runs on the caller's stack until its first await. It does not guarantee timer precision, since a timer's delay is a lower bound and the callback waits for the thread. The post on timer precision covers the clamping, throttling and drift that follow. It does not order tasks from different sources by anything you can rely on, such as a timer against a network response, since the relative order depends on timing outside your control.
The loop also does not protect you from races. Every await and every callback boundary is a gap in which other tasks can run, so state read before the gap may be stale after it. The post on race conditions in single-threaded JavaScript describes the patterns, and the fixes are to keep a check and its action in the same synchronous stretch, discard stale results with sequence numbers and serialize critical sections.
Debugging an ordering problem
When a log shows callbacks in an unexpected order, work through a short routine. Label each scheduling call with the queue it uses: mark promise callbacks, await continuations and queueMicrotask as "micro", and timers, I/O, events and setImmediate as "macro". In Node.js, add nextTick as its own category that goes first among the microtasks in CommonJS. Replay the program by hand with the three rules. Nearly every surprise comes from one of a few mistakes: counting an await as a task, forgetting that the whole script is the first task, forgetting that a microtask can queue more microtasks that all run before the next task, or assuming that a zero-delay timer runs "immediately".
If the paper replay and the real output disagree, check the environment. The order of a timer and setImmediate from the main module varies. The order of nextTick and promise callbacks differs between CommonJS and ES modules. A browser may paint before or after a zero-delay timer. In each case, the code should not depend on the order, and the fix is usually to express the dependency explicitly, by awaiting the thing you need instead of relying on queue order.
For problems that look like blocking, a profile finds the owner. In Chrome and Node.js, a CPU profile records which functions occupied the thread, and the flame chart shows a wide block where the loop was held. The block's function is the one to slice, move or replace.
Following one request through a Node.js server
Abstract rules are easier to trust once you have followed a real event through them. Take a small HTTP server that reads a file and answers with its contents, and trace what the loop does when a request arrives.
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
const server = createServer(async (request, response) => {
const text = await readFile("package.json", "utf8");
response.end(`read ${text.length > 0 ? "some" : "no"} bytes`);
});
server.listen(0, async () => {
const { port } = server.address();
const reply = await fetch(`http://127.0.0.1:${port}/`);
console.log(await reply.text());
server.close();
});read some bytesThe program assumes a package.json in the working directory. Here is the sequence, in terms of the loop. The script runs as the first task and calls listen, which asks the operating system to open a socket and returns. The script ends, the stack empties, and the loop goes into the poll phase, where it waits for events with nothing else to do, using no processor time.
When the socket is ready, libuv reports it, and the loop runs the listen callback as a task. That callback calls fetch, which opens a connection to the same process and returns a promise. The callback hits await, suspends and ends. Back in the poll phase, the loop is told that a connection arrived and that bytes can be read, and it runs the server's internal callbacks, which parse the request and emit the request event. Your handler runs as part of that task, calls readFile and reaches await, so it suspends. The file read is handed to a thread-pool thread, and the loop goes back to waiting.
When the pool thread finishes, it notifies the loop, a callback runs in the poll phase, the promise for readFile settles and a microtask resumes your handler, right after the callback that settled it. The handler calls response.end, which queues the write, and the handler returns, which fulfills its own promise. Over on the client side, the response bytes arrive in a later poll phase, the body stream delivers them, fetch resolves its promise and the original callback resumes in a microtask, prints the text and closes the server. When no sockets or timers remain, the loop has nothing to wait for, and the process exits.
Nothing in this trace ran in parallel with your JavaScript. The waiting was done by the operating system and the thread pool, and every piece of your code ran as part of a task or a microtask, one at a time. That is the pattern behind a server that handles thousands of connections: each connection is a few short tasks separated by long periods of waiting that cost the loop nothing.
Details that differ in the browser
The browser's loop has a few features worth knowing because they shape how pages behave.
Input gets priority. The HTML Standard lets the browser choose which task queue to take from next, and browsers use that freedom to run user input ahead of timers and network tasks when both are ready. That is why a page can stay responsive to clicks while timers are delayed, but only if tasks are short. A long task delays the input task like any other.
Hidden tabs are throttled. A tab the user cannot see has its timers throttled, and Chrome limits them to roughly one run per second, with stricter limits for tabs hidden for a long time. requestAnimationFrame callbacks stop altogether. Code that must keep running in the background, such as a countdown that compares against a deadline, should rely on timestamps and not on counting ticks.
Event handlers are tasks, with a twist. Each event listener runs in the task that dispatches the event, and the microtask checkpoint happens after each listener returns, when the stack is empty. If a click triggers button.click() from script, the listeners run synchronously inside your code, and the checkpoint is delayed until your own code finishes, which changes the order of promise callbacks compared with a real click.
const button = document.createElement("button");
button.addEventListener("click", () => {
Promise.resolve().then(() => console.log("microtask from listener 1"));
console.log("listener 1");
});
button.addEventListener("click", () => console.log("listener 2"));
button.click();
console.log("after click()");listener 1
listener 2
after click()
microtask from listener 1Because click() was called from a script, the stack was not empty between the listeners, so the microtask waited for the whole script to finish. With a real mouse click, the engine's stack is empty after listener 1 returns, and the output would put the microtask before listener 2. The distinction matters for code that depends on listener ordering, and it is a good reason to avoid relying on such interleaving.
Workers have their own loops. Each Web Worker has an event loop of its own, with its own task and microtask queues and no rendering step. Messages between a page and a worker are tasks in the receiving loop. A busy worker delays its own messages and nobody else's, which is the whole point of using one.
Message channels make quick macrotasks. MessageChannel and postMessage queue a task without the timer clamping that nested setTimeout calls suffer, and some schedulers use them to yield to the loop with less delay. The newer scheduler.yield() is the purpose-built version.
Misconceptions worth correcting
A handful of beliefs about the loop are widespread and cause real bugs.
*"Promises are asynchronous, so the function passed to new Promise runs later."* It does not. The executor runs immediately and synchronously. Only the handlers attached with then run later, as microtasks. A promise is a way of receiving a result, not a way of postponing work.
*"setTimeout(fn, 0) runs immediately."* It runs in a later task, after the current script and after all the pending microtasks, and the delay is clamped to at least 1 ms. When something must run right after the current code, use queueMicrotask.
*"await blocks."* It suspends the current function and nothing else. The thread continues with other work, and the function resumes when the promise settles.
"The loop checks for new tasks while my function runs." It cannot. Your function holds the only thread, and the loop regains control only when the stack is empty. A callback that was ready while your code ran has to wait for it.
*"Using more async makes the program faster."* It makes waiting overlap, and it adds a small cost per await. For code that never waits, it adds overhead and nothing else.
"The event loop is single-threaded, so Node.js is single-threaded." Your JavaScript is, and the process is not. libuv's pool, the garbage collector's helper threads and the operating system's own I/O machinery all run on other threads, and worker_threads adds more under your control.
Choosing a scheduling tool with the model in mind
With the model in hand, the question "which function should I use to run this later?" has a short answer for each situation. If the work must run right after the current code and before anything else, such as flushing a batch of synchronous updates, use queueMicrotask. If the work should wait for the loop to take a turn, such as breaking up a long computation, use a task: setImmediate in Node.js, scheduler.yield() or setTimeout in a browser. If it must happen before the next paint, use requestAnimationFrame. If it is background work that can wait for idle time, use requestIdleCallback or scheduler.postTask with a low priority. If it is a real delay, use setTimeout and remember that the delay is a lower bound.
The common thread is that each tool corresponds to a place in the loop, and choosing the right one means deciding which place your code belongs in. A function that runs too early, in a microtask, starves everything else, and one that runs too late, in a timer, adds latency. Matching the tool to the place is most of what "knowing the event loop" means in practice.


