Thuta Learning
JavaScript
AdvancedProgrammingBeginner

Async JS Intro

JavaScriptLesson 3325 min

What you'll walk away with

  • Explain that synchronous code runs one piece at a time on the call stack, and what blocking means
  • Predict that setTimeout(fn, 0) runs only after the stack is empty, not immediately
  • Know that Promise reactions (microtasks) run before timer callbacks (tasks)
  • Demonstrate that a CPU-heavy loop blocks the event loop

Explain it simply

Explain it simply

Picture a kitchen with only one cook. If the cook stands by the rice cooker until it finishes, nothing else gets cooked. So the cook sets a timer on the rice, keeps cooking the curry, and comes back when the timer rings. JavaScript works the same way: it has only one thread, but it hands slow jobs to the runtime and carries on.

Signals that something is done, such as a timer ringing, a server replying or a user clicking, wait in line. As soon as the cook's hands are free, the queued jobs are picked up one at a time. That endless check-and-pick cycle is called the event loop.

Problem → Why → Solution

The problem: a 0 ms timer, but the data is not there yet

This code fakes loading data from a server with setTimeout. The developer sets the delay to 0 ms, assumes "it will finish immediately", and reads user.name on the next line. The result is a TypeError, because user is still null. A delay of 0 ms does not mean "immediately"; it means "as soon as possible after the current code finishes".

load-user.js
let user = null;

setTimeout(() => {
  user = { name: "Aye Aye" }; // pretend this came from a server
}, 0);

console.log(user.name);
// TypeError: Cannot read properties of null (reading 'name')

Why is user still null?

setTimeout itself only registers the callback with the timer system and returns at once. The callback may run only after all the synchronous code on the call stack has finished. console.log(user.name) is part of that synchronous code, so it runs before the callback. To use an async result, you must use it inside the callback, or after a Promise settles.

Core concept: the call stack, two queues and the event loop

The JavaScript engine runs code on a single call stack. Every function call is pushed onto the stack and popped off when it returns, so only one piece of JavaScript runs at any moment. Waiting for timers, sending network requests, reading files and listening for clicks are not done by the engine itself: the runtime, the browser's Web APIs or Node.js's libuv, handles them outside the stack.

When the runtime finishes a job, it places the callback that should continue the work into a queue. There are two kinds. The task queue, also called the macrotask queue, receives timer callbacks, I/O callbacks and event handlers. The microtask queue receives Promise .then() callbacks, the code that continues after an await, and queueMicrotask() callbacks.

The event loop repeats one simple rule: as soon as the call stack is empty, drain the entire microtask queue, then take one task from the task queue and run it. That is why a Promise reaction runs even before a 0 ms timer.

text
The event loop
--------------
   +-------------+    hands off slow work    +---------------------+
   | Call stack  | ------------------------> | Runtime (Web APIs / |
   | (one thread)|                           | libuv): timers, I/O |
   +-------------+                           +---------------------+
          ^                                            |
          | event loop: when the stack is empty...     | when done
          |                                            v
   1. run ALL microtasks  <--  [ Promise .then, await, queueMicrotask ]
   2. then ONE task       <--  [ setTimeout, I/O, click handlers     ]

The key limitation is that the event loop can look at the queues only when the stack is empty. While a CPU-heavy synchronous loop runs, timers, clicks and even the browser's screen repaints all have to wait. Wrapping that loop in async or a Promise does not make it non-blocking; heavy computation has to move to a separate thread such as a Web Worker or Node.js's worker_threads. The other option is to split the work into small chunks, so the loop gets a chance to breathe between them.

Mental model: one turn of the event loop
  1. Run all synchronous code on the stack
  2. Stack empty: run every microtask
  3. Take one task from the task queue
  4. Repeat forever

A timer delay is a minimum wait, never an exact time.

General pattern

javascript
doSyncWork();                          // 1. runs now, on the stack

setTimeout(callback, delayMs);         // 4. task: after delay AND empty stack

promise.then(onResult);                // 3. microtask: right after sync code

queueMicrotask(() => { /* ... */ });   // 3. microtask as well

doMoreSyncWork();                      // 2. still part of the current run

Notice that the numbers in the comments do not follow the source order. All synchronous code finishes first, microtasks come next, and the timer task arrives last.

Example: the order of synchronous code, microtasks and timer tasks

Besides "Start", "End" and a two-second timer message, this example has a 0 ms timer and a Promise, so you also see how the two queues are prioritised. Before running it, predict the order of the five output lines.

event-loop.js
console.log("Start");

// setTimeout hands the callback to the runtime's timer system
setTimeout(() => {
  console.log("Timer: shown after about 1 second");
}, 1000);

// Even a 0 ms timer must wait until the call stack is empty
setTimeout(() => {
  console.log("Timer: 0 ms, but still after End");
}, 0);

// Promise reactions are microtasks: they run before timer tasks
Promise.resolve().then(() => {
  console.log("Microtask: promise reaction");
});

console.log("End");

Code breakdown

  1. Line 1console.log("Start");

    Synchronous, so it runs at once and becomes the first line of output.

  2. Lines 4-6}, 1000);

    setTimeout hands the callback to the timer system and returns immediately; setTimeout itself does not wait. The callback enters the task queue after at least one second.

  3. Lines 9-11}, 0);

    Despite the 0 ms, this callback is still a task. It may run only after all code on the stack and every microtask have finished, so it prints after "End".

  4. Lines 14-16Promise.resolve().then(() => {

    The Promise is already resolved, yet the .then() callback does not run immediately; it is queued as a microtask. Once the stack is empty, it runs before any timer task.

  5. Line 18console.log("End");

    Last in the source but synchronous, so it is the second line of output. Only after it finishes is the stack empty and the event loop free to check the queues.

You should see
Start
End
Microtask: promise reaction
Timer: 0 ms, but still after End
Timer: shown after about 1 second
What the event loop decides
  1. Run synchronous code to completion
  2. Check: is the call stack empty?
  3. Drain the whole microtask queue
  4. Run one task from the task queue

Microtasks waiting

Run them all before any task

No microtasks

Run the next task, then loop again

Blocking: a busy loop delays a timer

The code below sets a 10 ms timer and then runs a synchronous busy loop for 200 ms. The timer expires at 10 ms, but its callback cannot run while the loop occupies the stack. In a browser, clicks, scrolling and animations would all freeze for those 200 ms.

blocking.js
const started = Date.now();

setTimeout(() => {
  const waited = Date.now() - started;
  console.log(`Timer asked for 10 ms, waited ${waited >= 200 ? "200+" : "under 200"} ms`);
}, 10);

while (Date.now() - started < 200) {
  // busy loop: keeps the call stack occupied for 200 ms
}
console.log("Busy loop finished");

Looking ahead: from callbacks to async/await

There are three ways to handle async results: callbacks (the oldest), Promises, and async/await (the most common today). async/await is built on Promises and lets code read top to bottom like synchronous code. await pauses the function but does not block the thread; notice in the output below that the "Meanwhile" line runs while brewTea() is waiting. The next two lessons cover Promises and async/await in detail.

await-preview.js
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function brewTea() {
  console.log("Boil water");
  await wait(50); // pauses brewTea only, not the whole program
  console.log("Steep tea");
  await wait(50);
  console.log("Tea is ready");
}

brewTea().then(() => console.log("brewTea finished"));
console.log("Meanwhile: set the table");

In real projects

Where this shows up in real projects

Every web app is asynchronous: calling an API with fetch(), waiting for a button click and drawing animation frames all run through the event loop. A Node.js server handles thousands of requests on a single thread because, while it waits on a database or a file, it does not block the thread and keeps accepting new requests. But if one request handler does CPU work, such as parsing a huge JSON payload or hashing a password synchronously, the whole server slows down for every user.

Understanding the event loop order pays off when debugging. Questions like "why is this log out of order?" or "why has the state not updated yet?" usually come down to microtask versus task ordering. The Performance panel in browser DevTools marks long tasks, those over 50 ms, in red, so you can find the code that is blocking the page.

Common mistakes

Common mistakes

1. Using an async result on the very next line

A variable set inside a callback is not ready on the line right after the setTimeout or fetch call. Put the code that needs the result inside the callback, inside .then(), or after an await.

2. Treating a timer delay as an exact time

setTimeout(fn, 1000) only promises "at least 1000 ms". A busy stack or a background browser tab can make it later. When timing matters, as in a countdown, compute the real elapsed time with Date.now().

3. Believing async makes heavy code non-blocking

A loop of millions of iterations inside an async function still runs on the main thread and blocks the page. await can only give back time spent waiting; it does not speed up computation. Use a Web Worker or worker_threads.

Mini challenge

Mini challenge: predict the run order

Write fakeFetchUser(id, callback), which delivers a user after 50 ms. Then write a program combining it with one microtask, one 0 ms timer and two synchronous logs, and number every log line 1 to 5 in the order you expect them to run.

  • fakeFetchUser calls callback({ id, name }) through a 50 ms setTimeout
  • Log that the request was sent, synchronously, before calling fakeFetchUser
  • Add one Promise.resolve().then(...) and one setTimeout(..., 0)
  • When run, the logs must come out exactly in the order 1, 2, 3, 4, 5
run-order.js
function fakeFetchUser(id, callback) {
  // TODO: after 50 ms, call callback with { id, name }
}

// TODO: "1. request sent" (synchronous)
// TODO: call fakeFetchUser(1, ...) and log "5. user loaded: <name>"
// TODO: setTimeout(..., 0) that logs "4. timeout 0 ran"
// TODO: Promise.resolve().then(...) that logs "3. microtask ran"
// TODO: "2. still running synchronous code"

Expected: The logs must appear in numeric order: 1. request sent 2. still running synchronous code 3. microtask ran 4. timeout 0 ran 5. user loaded: Aye Aye

Show hint

Source order and run order differ. Number the logs using the rule: synchronous logs first, then the microtask, then the 0 ms timer, and the 50 ms timer last.

Show solution
run-order.js
function fakeFetchUser(id, callback) {
  setTimeout(() => {
    callback({ id, name: id === 1 ? "Aye Aye" : "Unknown" });
  }, 50);
}

console.log("1. request sent");
fakeFetchUser(1, (user) => console.log(`5. user loaded: ${user.name}`));
setTimeout(() => console.log("4. timeout 0 ran"), 0);
Promise.resolve().then(() => console.log("3. microtask ran"));
console.log("2. still running synchronous code");

Quick quiz 1 / 3

What order does this print? console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D");

Quick quiz 2 / 3

What does setTimeout(fn, 1000) guarantee?

Quick quiz 3 / 3

In a browser, what happens while a click handler runs a synchronous loop that takes 3 seconds?

What to remember

  • JavaScript runs on a single call stack and hands slow work to the runtime (Web APIs or libuv).
  • When the stack is empty, the event loop runs every microtask first, then one task.
  • setTimeout(fn, 0) runs after synchronous code and Promise reactions; a delay is only a minimum.
  • CPU-heavy work blocks the event loop, and adding async does not fix it; use a worker.

MDN — Asynchronous JavaScript — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Async JS Intro | Thuta Learning