Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 156 ยท Asynchronous JavaScript

How Asynchronous JavaScript Works

Understand how single-threaded JavaScript handles waiting: the call stack, the event loop, task and microtask queues, and predicting output order.

JavaScript runs your code on a single thread. It does one thing at a time, one line after another. Yet web pages wait for network responses, timers and clicks all the time without freezing. How can one thread wait for many things at once?

The answer is that JavaScript doesn't wait. It hands slow jobs to the browser (or Node.js), keeps running, and picks up the results later through a mechanism called the event loop. Understanding the event loop explains why setTimeout(fn, 0) doesn't run immediately, why a long loop freezes a page, and in exactly which order your asynchronous code will run. Every lesson in this chapter builds on it.

Synchronous code runs to completion

Code is synchronous when each line finishes before the next one starts. Most of what you've written so far is synchronous. JavaScript keeps track of which function is running with the call stack: calling a function pushes it on the stack, returning pops it off.

The important rule is this: once a piece of JavaScript starts running, nothing can interrupt it until the call stack is empty. No timer callback, no click handler, nothing. That's called run-to-completion.

This is easy to see with a deliberately slow loop. It keeps the thread busy for a moment, so the timer that was due almost immediately has to wait:

JS Busy code blocks everything

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The timer was ready after 10 ms, but it couldn't run until the loop finished and the stack was empty. In a real page, the same thing happens to clicks, scrolling and animations: a long-running script makes the whole tab feel frozen.

The browser does the waiting

So who counts down the timer while your loop runs? Not JavaScript. When you call setTimeout(), fetch() or addEventListener(), you are asking the host environment (the browser, or Node.js) to do something on your behalf. The browser has its own threads for timers, networking and input. JavaScript just registers a callback, a function to call when the work is done, and moves on.

When the timer expires or the response arrives, the browser doesn't call your function right away, because JavaScript might be busy. Instead it puts the callback into a queue to be run later.

The event loop

The event loop is the simple process that connects the queues to the call stack. In plain words, it repeats forever:

  1. Take the oldest task from the task queue and run it to completion.
  2. Run every microtask in the microtask queue, including any new ones added along the way, until that queue is empty.
  3. If it's time, let the browser render (update the screen).
  4. Go back to step 1.

Running your main script is itself the first task. So everything scheduled during the script only runs after the script has completely finished.

There are two queues, and the difference between them is the key to predicting output:

Queue Also called Filled by Runsโ€ฆ
Task queue macrotask queue, callback queue setTimeout, setInterval, events (clicks, keys), messages, network callbacks one task per loop turn
Microtask queue job queue promise callbacks (then, catch, finally, code after await), queueMicrotask(), MutationObserver all of them, right after the current task, before anything else

Microtasks are "urgent follow-ups": they run as soon as the current code finishes, before the next timer or event gets a turn, and before the browser repaints.

Predicting the order

Time to put this to work. Before you press Run, write down the order you expect the five lines to appear in:

JS Predict the order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output is A, E, C, D, B. Here's why:

  1. A logs. Synchronous.
  2. setTimeout hands a timer to the browser. Even with a delay of 0, the callback B goes into the task queue.
  3. Promise.resolve() is already fulfilled, so its .then callback C goes straight into the microtask queue.
  4. queueMicrotask puts D in the microtask queue, behind C.
  5. E logs. The script (the first task) is done and the stack is empty.
  6. The event loop drains the microtask queue: C, then D.
  7. Only now does the next task run: B.

queueMicrotask(fn) is the direct way to schedule a microtask without creating a promise. It works in all modern browsers and Node.js. You'll learn promises properly in Promises; here they are just a convenient way to create microtasks.

setTimeout(fn, 0) means "as soon as possible, but later". It never runs immediately. It always waits for the current code and every pending microtask to finish first, and browsers may add a few milliseconds on top. See setTimeout and setInterval.

Microtasks run between tasks

Because the microtask queue is drained after every task, microtasks scheduled inside a timer callback run before the next timer. And microtasks scheduled by other microtasks run in the same drain, still before any timer:

JS Tasks and microtasks interleaved

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output is:

TEXT
sync: script done
a. first microtask
b. microtask added by a microtask
1. timeout one
2. microtask from timeout one
3. timeout two

Work through it with the four loop steps. The script is task one. Its microtasks (a, then the b that a adds) drain completely. Then the first timer task runs, and its microtask (2) drains before the second timer task gets its turn.

A harder one

Try predicting this before running it. Hint: a callback isn't queued until the thing it waits for actually happens.

JS Challenge: predict the output

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The answer is 1, 7, 3, 6, 5, 2, 4. The first .then (logging 3) and queueMicrotask (logging 6) are queued during the script. The second .then (logging 5) is only queued after the first one finishes, so it lands behind 6. Timer 2 was queued during the script; timer 4 was only created while the microtasks ran, so it comes last.

Why this matters for the page

Rendering happens between tasks, never in the middle of one. That has practical consequences:

  • Long tasks freeze the page. Nothing repaints and no click is handled until the current task ends. Aim to keep each task short, ideally well under 50 ms.
  • Microtasks can starve the page too. Since the microtask queue must be completely empty before rendering, a microtask that keeps scheduling another microtask blocks the page forever, just like an infinite loop.
  • Splitting work helps. Breaking a big job into chunks with setTimeout gives the browser a chance to repaint and respond between chunks.

Click Count below, then click Ping while it runs. The blocking version freezes everything; the chunked version stays responsive:

Blocking vs chunked work

Notice that the blocking version never even shows "Working (blocking)...": the text was set, but the browser couldn't repaint until the task ended, by which time the text had changed again. Your Ping clicks were queued as tasks and all ran afterwards. Truly heavy computation belongs in a Web Worker, which runs JavaScript on a separate thread, but chunking is often enough.

Node.js and other environments

Node.js uses the same model: one JavaScript thread, an event loop, tasks and microtasks. Its loop has a few extra phases (for file I/O, setImmediate and more) and an extra queue for process.nextTick() that runs even before promise microtasks. For everyday code, the browser rules you learned here predict Node.js behavior too.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is logged? setTimeout(() => console.log("T"), 0); Promise.resolve().then(() => console.log("P")); console.log("S");

    Synchronous code first (S), then all microtasks (P), then the next task, the timer (T).
  2. 2. When does the event loop run microtasks?

    The microtask queue is drained completely after each task (including the main script).
  3. 3. A while loop runs for 2 seconds. A setTimeout with a 100 ms delay was set just before it. When does the timer callback run?

    JavaScript runs to completion; the timer callback waits in the task queue until the stack is empty.
  4. 4. Which of these does NOT add a microtask?

    setTimeout schedules a task (macrotask), not a microtask.
  5. 5. Why can't the browser repaint while a long synchronous loop runs?

    The event loop renders between tasks. A task that never ends never gives rendering a turn.

Summary

  • JavaScript runs on a single thread, and each piece of code runs to completion without interruption.
  • The browser or Node.js does the actual waiting (timers, network, input) and queues callbacks when they're ready.
  • The event loop runs one task, then drains all microtasks, then may render, then repeats.
  • Timers and events are tasks; promise callbacks and queueMicrotask are microtasks, which always run first.
  • Synchronous code โ†’ microtasks โ†’ the next task: use this to predict output order.
  • Long tasks and endless microtasks freeze the page; split heavy work into chunks or move it to a Web Worker.

Next: setTimeout and setInterval โ€” schedule code, cancel it, and build debounce and throttle helpers.