JavaScript path · Async · Topic 8 of 12

Tasks vs microtasks

Not started

Tasks (timers, user input, network and I/O callbacks, postMessage) run one per turn of the loop. Microtasks (promise callbacks, queueMicrotask, MutationObserver) all run before the loop moves on, including any new ones they add. requestAnimationFrame callbacks are separate again: they run just before the browser paints.

Why it matters: A chain of microtasks that keeps adding more can starve rendering and input completely, while a timer would let the page breathe.

1

How it works

The explanation, with examples you can run.

Who goes first

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

The script itself is a task. When it ends, both microtasks run, in the order they were queued, and only then does the loop take the timer.

Starving the loop

Because the microtask queue must be empty before anything else happens, microtasks that keep queueing more can hold everything up. Here a due timer waits for 100,000 microtasks:

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

Choosing one

  • Use a microtask (queueMicrotask, or just a promise) when something must happen right after the current code, before anything else can observe the state in between.
  • Use a task (setTimeout, or postMessage) to break long work into pieces so input and painting can happen between them.
  • Use requestAnimationFrame for visual updates you want in the next frame.
2

Check yourself

2 questions. Get them all right to finish this topic.

  1. 1.Which of these runs as a microtask?
  2. 2.A microtask keeps queueing another microtask forever. What happens to a timer that is due?

0 of 2 right so far. Get all two to finish this topic.