Sync vs Async JavaScript
Understand the call stack, promises, and the event loop through an interactive visualization you can edit and rerun.
JavaScript is single threaded and non blocking, which can feel contradictory on first read. The truth is in how the engine coordinates with browser APIs and the event loop.
The walkthrough below keeps the focus on the mechanics rather than the theory. Read each section, then change the code and watch the queues react.
Synchronous JavaScript and the Call Stack
The call stack keeps track of where the engine is in your code. Each function is pushed onto the stack, executed, then removed.
- Push function calls are added to the top.
- Execute the engine runs the current frame.
- Pop when finished, it removes the function.
function f1() {
// executes...
}
function f2() {
f1();
}
f2();Asynchronous JavaScript and the Event Loop
Promises and timers do not block the stack. They schedule work in separate queues and the event loop decides when those tasks can run.
Call Stack
Browser APIs
Job Queue Micro
Callback Queue Macro
Rules to Remember
Call Stack Priority
The engine always finishes the call stack before pulling from any queue.
Browser APIs
Timers hand work to the browser and return immediately so the stack can continue.
Microtasks
Promise callbacks run before macrotasks. The microtask queue is fully drained first.
Macrotasks
The event loop runs one callback queue task, then checks microtasks again.