Core Mechanics & Execution Model:
- Single-Threaded Runtime: JavaScript executes on a single call stack. The Event Loop coordinates asynchronous non-blocking I/O operations by delegating tasks to browser/Node APIs and processing queued callbacks.
1. Execution Phases:
- Call Stack: Synchronous code executes immediately until the stack is completely empty.
- Microtask Queue: Highest priority queue. Drained completely after every synchronous turn and before the browser renders or processes the next macrotask.
- Microtasks include: Promise.then/catch/finally, queueMicrotask(), MutationObserver, and in Node.js, process.nextTick() (which runs even before standard microtasks).
- Macrotask (Task) Queue: Lower priority queue. Processes one single task per loop iteration.
- Macrotasks include: setTimeout, setInterval, setImmediate, I/O operations, UI rendering events.
2. Execution Flow Sequence:
- 1. Execute one script / macrotask from the queue.
- 2. Drain ALL microtasks until the microtask queue is empty (even if microtasks schedule new microtasks).
- 3. Execute UI render/re-paint if needed.
- 4. Move to the next macrotask in the queue.