How it works
The explanation, with examples you can run.
Who goes first
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:
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, orpostMessage) to break long work into pieces so input and painting can happen between them. - Use
requestAnimationFramefor visual updates you want in the next frame.
Check yourself
2 questions. Get them all right to finish this topic.
0 of 2 right so far. Get all two to finish this topic.