← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 7 of 26

JS Event Loop

What Is the Event Loop?

The event loop helps JavaScript handle asynchronous work while the main thread remains available. This lets JavaScript remain single-threaded and non-blocking at the same time — long-running I/O doesn't freeze the page, because it's handled outside the main synchronous flow.

Example: What Is the Event Loop?

javascript
console.log("1");
setTimeout(() => console.log("2"), 0);
console.log("3"); // 1, 3, 2 - main thread finishes first

Call Stack

JavaScript runs synchronous function calls on the call stack. Only once the call stack is completely empty does the event loop pull the next task from a queue and push it onto the stack to run.

Example: Call Stack

javascript
function a() { b(); }
function b() { console.log("on the call stack"); }
a();

Task Queue

Timer callbacks and many browser callbacks wait in queues before the event loop runs them. These queued callbacks don't run immediately, even with a 0ms delay — they wait for the current synchronous code to finish and the call stack to clear first.

Example: Task Queue

javascript
console.log("start");
setTimeout(() => console.log("from queue"), 0);
console.log("end"); // queued callback waits for the stack to clear

Microtasks

Promise callbacks are microtasks. They normally run before timer callbacks after current code finishes. Because microtasks are drained completely before the next task queue item runs, a chain of resolved Promises can execute before a setTimeout(fn, 0) callback even one tick later.

Example: Microtasks

javascript
console.log("1");
Promise.resolve().then(() => console.log("2 - microtask"));
setTimeout(() => console.log("3 - timer"), 0);
console.log("4");

Practical Order

Understanding execution order helps you predict asynchronous JavaScript output. This ordering explains output that looks surprising at first glance, like a Promise handler logging before a setTimeout scheduled earlier in the code.

Example: Practical Order

javascript
console.log("A");
setTimeout(() => console.log("B - timer"), 0);
Promise.resolve().then(() => console.log("C - microtask"));
console.log("D");
// Order: A, D, C, B

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.