Skip to the workspace
Pebellslearn by building
Asynchronous JavaScript  ›  Lesson

The Event Loop

Asynchronous JavaScript 12 min

javascript / The Event Loop

Explore each scene at your own pace.

01 · The Event Loop

The Event Loop

The Event Loop

The event loop coordinates queued work with JavaScript execution. A running job completes before another job runs; promise reactions use microtasks, which run before the next timer task in this example.

Scheduling a zero-delay timer does not interrupt the code that is already running.

See the mechanism

Walk through the modelThe Event LoopAuthored snapshots of the example; use Run below to test the code.
outputA, B
timerpending
promise reactionqueued
Neither deferred callback interrupts the running execution.
1 of 3

Follow one example

javascript

A and B print during the current execution. After it finishes, the promise reaction runs as a microtask. The timer callback runs in a later task. Zero delay is not an exact execution deadline. This is a simplified ordering example; hosts have multiple task sources and rendering opportunities, and heavy synchronous work still blocks progress on its thread.

Predict, change and check

Predict: Will registering the timer before the promise cause timer to print first?

Test your explanation: Reverse their registration order and check the output. Keep callbacks small, and do not use a chain of microtasks as a way to yield reliably to rendering.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Trace turns and microtasks separately

In a browser, current synchronous work completes before queued promise reactions run. A timer callback normally waits for a task opportunity after the relevant microtask checkpoint. A long chain of microtasks can delay other tasks and rendering; moving work into Promise.resolve().then does not create a background CPU thread.

Do not generalize the browser diagram to every Node scheduling phase. Rendering opportunities and host queues have their own rules, and a zero-delay timer is not an exact timestamp. Predict relative order in a deliberately controlled example; use a trace rather than a guessed delay when investigating a real responsiveness problem.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.