Event Loop & Async
Published by Brayan K
The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous work by continuously taking queued callbacks — microtasks like Promises first, then macrotasks like timers — and running them once the call stack is empty.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Separate work that runs now from work that is queued
A scheduled callback cannot interrupt the currently running synchronous code in these examples. Once that work gives control back, ready microtasks are processed at a microtask checkpoint before a later timer task runs. The examples use one timer or explicitly controlled promises, print no elapsed time and make no claim about an exact delay.
console.log("start");
const timerDone = new Promise(resolve => {
setTimeout(() => {
console.log("timer"); // A later task, not an immediate call.
resolve();
}, 0);
});
queueMicrotask(() => console.log("microtask")); // Queued until current work yields.
console.log("end");
await timerDone; // Keep this complete example alive until its timer has run.
// ✅ Expected output:
// start
// end
// microtask
// timerZero is a requested timer delay, not permission to run in the middle of the current code. The final await lets the complete example observe the callback; it does not make the timer exact. Deep Dive into JavaScript Execution Context & Call Stack owns synchronous call/return paths.
Ready microtasks run in queue order, including work they add
queueMicrotask(() => {
console.log("A");
queueMicrotask(() => console.log("C"));
});
queueMicrotask(() => console.log("B"));
await new Promise(resolve => setTimeout(resolve, 0));
// ✅ Expected output:
// A
// B
// CC is added while A is running, after B was already queued. The checkpoint continues processing microtasks that are added by other microtasks. This is why repeatedly adding more can postpone later tasks. The demonstration below stops after three iterations rather than creating a page-freezing infinite loop.
let remaining = 3;
function step() {
console.log("microtask", remaining);
remaining--;
if (remaining > 0) queueMicrotask(step);
}
queueMicrotask(step);
await new Promise(resolve => {
setTimeout(() => { console.log("timer"); resolve(); }, 0);
});
// ✅ Expected output:
// microtask 3
// microtask 2
// microtask 1
// timerThis output is about ordering, not duration. An unbounded self-scheduling microtask chain could prevent the checkpoint from finishing. More microtasks are not a general way to make a user interface responsive.
A promise reaction is queued when its promise can settle
A promise executor runs synchronously when the Promise is constructed. A then handler runs later as a promise reaction. Mastering Promises: Chaining, Error Flow & Patterns owns construction and chaining; here we compare the execution order.
console.log("before");
const promise = new Promise(resolve => {
console.log("executor");
resolve("ready");
});
const observed = promise.then(value => console.log("reaction", value));
console.log("after");
await observed;
// ✅ Expected output:
// before
// executor
// after
// reaction readyA then registered on a still-pending promise is not a ready callback that can “beat” any timer. If the timer settles that promise, the reaction cannot run before the settlement happens:
let release;
const pending = new Promise(resolve => { release = resolve; });
const observed = pending.then(() => console.log("reaction"));
queueMicrotask(() => console.log("ready microtask"));
setTimeout(() => {
console.log("timer starts");
release();
console.log("timer ends");
}, 0);
await observed;
// ✅ Expected output:
// ready microtask
// timer starts
// timer ends
// reactionThe timer callback finishes its synchronous statements before the newly ready reaction runs. “Promises always win” hides this dependency and is not a useful general rule.
Awaiting an already-ready value does not create a new timer task
const timerDone = new Promise(resolve => {
setTimeout(() => { console.log("timer"); resolve(); }, 0);
});
for (let index = 0; index < 3; index++) {
await Promise.resolve();
console.log("iteration", index);
}
console.log("loop complete");
await timerDone;
// ✅ Expected output:
// iteration 0
// iteration 1
// iteration 2
// loop complete
// timerawait suspends this async flow and resumes it through promise machinery. Awaiting a resolved promise does not guarantee an opportunity for browser rendering or another task between every iteration. Async/Await owns value and rejection flow; JavaScript Performance Optimization Techniques owns practical work chunking and profiling.
Invoking a callback and queuing a callback are different operations
function work() { console.log("work runs"); }
try {
queueMicrotask(work());
} catch (error) {
console.log(error.name);
}
console.log("after request");
// ✅ Expected output:
// work runs
// TypeError
// after requestwork() runs immediately and returns undefined, which is not a callback. The checked runtimes both throw TypeError but phrase the full platform diagnostic differently, so this caught case prints the actual error name. Pass work itself to queue it:
function work() { console.log("work runs"); }
queueMicrotask(work);
console.log("after request");
await new Promise(resolve => setTimeout(resolve, 0));
// ✅ Expected output:
// after request
// work runsA catch surrounding scheduling has already finished when a later callback runs. Handle a failure at that callback’s execution boundary or use a promise flow whose rejection is observed. Callbacks & Callback Hell and Error Handling own those boundaries.
const finished = new Promise(resolve => {
queueMicrotask(() => {
try {
throw new Error("Queued work failed");
} catch (error) {
console.log(error.message);
} finally {
resolve();
}
});
});
console.log("scheduled");
await finished;
// ✅ Expected output:
// scheduled
// Queued work failedCancellation depends on which queue you used
let ran = false;
const timer = setTimeout(() => { ran = true; }, 0);
clearTimeout(timer);
await new Promise(resolve => setTimeout(resolve, 0));
console.log(ran);
// ✅ Expected output:
// falseThe timer handle is deliberately not printed: its representation differs between browsers and Node. queueMicrotask has no corresponding cancellation handle. A queued callback can instead check whether its owner is still active and skip the work.
let active = true;
queueMicrotask(() => {
if (!active) {
console.log("skipped");
return;
}
console.log("work");
});
active = false;
await new Promise(resolve => setTimeout(resolve, 0));
// ✅ Expected output:
// skippedThe callback still ran to check the flag. That is different from removing an entry from a queue or canceling an underlying network operation. AbortController & Cancelling Async Work owns cooperative cancellation signals.
Batch updates without losing work added during delivery
A microtask can coalesce several synchronous updates into one delivery. Keep a pending list and a scheduling flag. Before calling the consumer, detach that list and clear the flag so a reentrant add can schedule a separate delivery instead of disappearing into an already-delivered buffer.
function createBatcher(deliver) {
if (typeof deliver !== "function") throw new TypeError("deliver must be a function");
let scheduled = false;
let pending = [];
return value => {
pending.push(value);
if (scheduled) return;
scheduled = true;
queueMicrotask(() => {
scheduled = false;
const batch = pending;
pending = [];
deliver(batch);
});
};
}
createBatcher(null);
// ✅ Expected error:
// TypeError: deliver must be a functionThis is a small scheduling contract, not a framework rendering policy. Its consumer is synchronous and non-throwing. A real component must also decide what disposal means and how consumer failures are reported. The final brief adds an explicit close operation.
Browser rendering and Node scheduling need their own scope
A browser may update rendering after a microtask checkpoint, but it does not promise a paint after every callback or timer. requestAnimationFrame is tied to a rendering opportunity and may be paused in a background context; it is not simply a universally higher-priority task queue. Console workers do not have a DOM to paint.
Browsers have multiple task sources, and Node has its own phases and scheduling APIs. These portable snippets establish their displayed orders, not a single priority table for every host API. Web Workers (Background Threads) owns worker execution; Performance Optimization owns measuring a user-visible workload.
Guided exercise: coalesce synchronous additions
Complete the scheduling call, the flag reset and the detached batch. The consumer should receive both synchronous additions in one delivery.
let scheduled = false;
let pending = [];
function add(value) {
pending.push(value);
if (scheduled) return;
scheduled = true;
___(() => { // 👉 replace ___ with queueMicrotask
scheduled = ___; // 👉 replace ___ with false
const batch = ___; // 👉 replace ___ with pending
pending = [];
console.log(batch.join(","));
});
}
add("A");
add("B");
console.log("added");
await new Promise(resolve => setTimeout(resolve, 0));
// ✅ Expected output:
// added
// A,BIndependent brief: a batcher with reentry and close rules
Write createBatcher(deliver), requiring a synchronous, non-throwing function or throwing TypeError("deliver must be a function"). Return add(value) and close(). Multiple additions before delivery form one array in insertion order. An add during deliver schedules a separate later batch. Before delivery, detach the pending array and clear the scheduled flag.
close marks the batcher closed and discards pending values. Already queued callbacks must return without delivering. Repeated close is harmless. Any add after close throws Error("Batcher is closed"). Check synchronous coalescing, reentrant addition, closing before delivery and the closed-input error. Use a timer only to wait for these finite microtask chains; print no elapsed time.
function createBatcher(deliver) {
if (typeof deliver !== "function") throw new TypeError("deliver must be a function");
let closed = false;
let scheduled = false;
let pending = [];
return {
add(value) {
if (closed) throw new Error("Batcher is closed");
pending.push(value);
if (scheduled) return;
scheduled = true;
queueMicrotask(() => {
scheduled = false;
if (closed) return;
const batch = pending;
pending = [];
deliver(batch);
});
},
close() {
closed = true;
pending = [];
}
};
}
const delivered = [];
let batcher;
batcher = createBatcher(batch => {
delivered.push(batch.join(","));
if (batch.includes("A")) batcher.add("later");
});
batcher.add("A");
batcher.add("B");
await new Promise(resolve => setTimeout(resolve, 0));
console.log(delivered.join(" | "));
batcher.add("discard");
batcher.close();
batcher.close();
await new Promise(resolve => setTimeout(resolve, 0));
console.log(delivered.join(" | "));
try { batcher.add("closed"); } catch (error) { console.log(error.message); }
// ✅ Expected output:
// A,B | later
// A,B | later
// Batcher is closedThe first delivery receives A and B. Its reentrant addition goes into a new buffer and a later microtask. Closing prevents the queued discard batch from being delivered. This contract does not await an asynchronous consumer and does not claim that batching guarantees a faster interface.
Practice quiz
What does this complete program print? const done = new Promise(resolve => setTimeout(() => { console.log("timer"); resolve(); }, 0)); queueMicrotask(() => console.log("microtask")); console.log("sync"); await done;
- sync microtask timer
- timer microtask sync
- sync timer microtask
- microtask sync timer
Answer: sync microtask timer. The current synchronous work finishes, then the ready microtask, then the later timer task.
What does this complete program print? queueMicrotask(() => { console.log("A"); queueMicrotask(() => console.log("C")); }); queueMicrotask(() => console.log("B")); await new Promise(resolve => setTimeout(resolve, 0));
- A C B
- A B C
- B A C
- C A B
Answer: A B C. The nested callback joins after B, which was already queued.
What does this complete program print? const observed = new Promise(resolve => { console.log("executor"); resolve(); }).then(() => console.log("reaction")); console.log("sync"); await observed;
- sync executor reaction
- executor reaction sync
- executor sync reaction
- reaction executor sync
Answer: executor sync reaction. The executor runs during construction; the reaction is deferred.
What does this complete program print? let release; const pending = new Promise(resolve => { release = resolve; }); const observed = pending.then(() => console.log("reaction")); setTimeout(() => { console.log("timer"); release(); }, 0); await observed;
- reaction timer
- reaction
- timer
- timer reaction
Answer: timer reaction. A reaction on a pending promise cannot run before the timer settles it.
What does this complete program print? let ran = false; const timer = setTimeout(() => { ran = true; }, 0); clearTimeout(timer); await new Promise(resolve => setTimeout(resolve, 0)); console.log(ran);
- false
- true
- undefined
- 0
Answer: false. The handle is canceled before the callback can run.
What does this complete program print? let active = true; queueMicrotask(() => console.log(active ? "work" : "skipped")); active = false; await new Promise(resolve => setTimeout(resolve, 0));
- work
- skipped
- undefined
- false
Answer: skipped. The callback reads the current flag when it eventually runs.
What does this complete program print? const timer = new Promise(resolve => setTimeout(() => { console.log("timer"); resolve(); }, 0)); await Promise.resolve(); console.log("continued"); await timer;
- timer continued
- timer
- continued timer
- continued
Answer: continued timer. Awaiting an already-fulfilled promise resumes through microtasks before this waiting timer.
What does this complete program print? let scheduled = false, queued = 0; function add() { if (scheduled) return; scheduled = true; queued++; queueMicrotask(() => { scheduled = false; }); } add(); add(); add(); console.log(queued); await new Promise(resolve => setTimeout(resolve, 0));
- 0
- 2
- 3
- 1
Answer: 1. The scheduling flag coalesces all three synchronous calls into one queued delivery.
Continue this course
- Previous: Advanced Scope, Closures & Lexical Environments
- Next: Mastering Promises: Chaining, Error Flow & Patterns — Chain promises, handle errors correctly, and use Promise.all/race
- Quick reference: JavaScript cheat sheet