JavaScript is single-threaded, yet it powers highly interactive, non-blocking applications. The secret is the Event Loop.
At a high level, JavaScript executes code in three phases:
synchronous code β microtasks β macrotasks β and repeats this cycle continuously.
The call stack runs all synchronous code first. Once empty, the engine immediately drains the microtask queue, which contains Promise reactions (then, catch, finally) and async/await continuations. Only after all microtasks finish does the engine execute *one macrotask *(such as setTimeout, setInterval, or a UI event). Then the process repeats.
This strict priority model prevents race conditions and ensures application state is always consistent before timers or UI updates occur.
Example
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
Output
A
D
C
B
Why?
Because Promises (microtasks) always run before timers (macrotasks).
Understanding this model unlocks better debugging, predictable behavior, and high-performance UI development β especially in modern frameworks like React and Vue where state consistency is critical.
Master the Event Loop, and you master JavaScript.
Top comments (0)