The JavaScript event loop is the mechanism that lets JavaScript handle asynchronous, non-blocking operations even though the language itself runs on a single thread. It continuously coordinates:
setTimeout.Promise.then callbacks.In short, the event loop:
JavaScript does not expose the event loop directly via syntax, but you interact with it using:
setTimeout, setInterval → schedule macrotasks.Promise.then, async/await → schedule microtasks.A typical flow looks like this:
setTimeoutThis example shows how a timer callback is delayed until after synchronous code finishes:
console.log("Start");
setTimeout(() => {
console.log("Timeout callback");
}, 0);
console.log("End");
// Expected output:
// Start
// End
// Timeout callback
Here we compare setTimeout (macrotask) with a resolved Promise (microtask):
console.log("Script start");
setTimeout(() => console.log("setTimeout"), 0);
Promise.resolve().then(() => console.log("Promise then"));
console.log("Script end");
// Expected output:
// Script start
// Script end
// Promise then
// setTimeout
Start End Timeout callback
Even though setTimeout(..., 0) uses a delay of 0 milliseconds, its callback is placed in the callback queue and will only be executed after:
console.log("Start"), console.log("End")) finishes.Script start Script end Promise then setTimeout
The microtask (Promise.then) runs before the macrotask (setTimeout), which is why Promise then appears before setTimeout in the output.
Both browsers and Node.js use the event loop idea but their implementations differ slightly:
process.nextTick) are also woven into these phases.Click the button to see the execution order produced by the event loop in real time:
Click the button to generate logs.
requestAnimationFrame while keeping the page responsive.requestIdleCallback where possible.setTimeout(fn, 0) runs immediately; it waits for the current stack and microtasks to complete.setTimeout and Promise.then and predict the output order before running it in the console.while loop that runs for a few seconds and observe how timers and UI interactions are delayed.async function that awaits a Promise and log the order of messages around it.process.nextTick and setImmediate and compare when their callbacks run.