JS Event Loop
In this page:
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?
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
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
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
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
console.log("A");
setTimeout(() => console.log("B - timer"), 0);
Promise.resolve().then(() => console.log("C - microtask"));
console.log("D");
// Order: A, D, C, B
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML