typestar

Microtasks and macrotasks in JavaScript

Promises jump the queue: every microtask runs before the next timer.

console.log("1 synchronous");

setTimeout(() => console.log("5 timeout"), 0);

Promise.resolve().then(() => console.log("3 microtask"));
queueMicrotask(() => console.log("4 queueMicrotask"));

console.log("2 synchronous end");

// prints 1, 2, 3, 4, 5 -- the timer is last even at zero delay

How it works

  1. Synchronous code finishes first, always.
  2. Then the microtask queue drains: promises and queueMicrotask.
  3. Only then does a timer callback get its turn.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
291
Tokens
62
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 35 seconds.

Type this snippet

Step 1 of 3 in Scheduling, step 12 of 19 in Promises & async.

← Previous Next →