The Event Loop
The event loop is what allows JavaScript (single-threaded) to handle async operations. It constantly checks the call stack and task queues.
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
console.log("End");
Try it Yourself →
Call Stack & Task Queue
The call stack runs synchronous code. Async callbacks (like setTimeout) go to the task queue and run only after the stack is empty.
function a() {
b();
}
function b() {
console.log("Inside B");
}
a();
console.log("Global end");
Try it Yourself →
Microtasks vs Macrotasks
Promise callbacks are microtasks — they run before macrotasks (setTimeout, setInterval). Microtasks have higher priority.
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
Try it Yourself →