Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

JS
JavaScript
0/12 completed
Beginner
What is JavaScript?Variables and data typesOperators and expressionsMaking decisions: if and switchLoops
Intermediate
FunctionsArrays and array methodsObjects
Advanced
Scope and closuresClasses and OOPPromises and async/await
Pro
The event loop
Tracks / JavaScript / Pro

The event loop

JavaScript runs on a single thread: it can only do one thing at a time. Yet it handles thousands of network requests, timers and clicks. The secret is the event loop. Understanding it explains "weird" output order, frozen pages, and how Node.js scales.

The pieces

  1. Call stack: the function that's running right now, plus whoever called it.
  2. Web APIs / Node APIs: timers, network and file I/O handled outside your JavaScript.
  3. Task queue (macrotasks): callbacks from setTimeout, I/O and UI events.
  4. Microtask queue: promise callbacks (.then, await continuations) and queueMicrotask.

The loop: run everything on the stack → then run all microtasks → then take one task → repeat.

Predict the output

Before pressing Run, write down the order you expect.

JavaScript · editable

Why:

  • A and F are synchronous, so they run first.
  • C and E are microtasks; they run as soon as the stack is empty. D was queued when C finished, so it runs right after.
  • B is a task. Even with a 0 ms delay, it waits until every microtask is done.

await is just a microtask

JavaScript · editable

Everything after await is scheduled as a microtask. Microtasks run in the order they were queued, and all of them run before the setTimeout task.

Blocking the loop

Since there's one thread, long synchronous work blocks everything: timers, clicks and rendering.

JavaScript · editable

In a browser, this would freeze the page. In a Node.js server, every user would wait.

How pros avoid blocking

  • Split work into chunks and yield with setTimeout/await between them.
  • Move heavy computation to a Web Worker (browser) or worker thread (Node). The code editors on this site do exactly that!
  • Use async I/O APIs, never sync ones like fs.readFileSync inside a server request.
JavaScript · editable

Microtask starvation

Because the loop drains all microtasks before the next task, a microtask that keeps scheduling more microtasks will starve timers forever. Recursive setTimeout doesn't have this problem.

Practice

Predict the exact output order, then run it to check.

JavaScript · editable
✎ Check your understanding

1.Which runs first after the current script finishes: a resolved promise's .then or a setTimeout(fn, 0)?

2.Why is a long synchronous loop bad in a Node.js server?

← Promises and async/await