Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.3 — The Event Loop
JavaScript · Example 2 of 4

Each task gets its own microtasks

The microtask created inside timer 1 runs before timer 2, because the microtask queue is emptied after every task.

The event loop is the rule that decides what runs next: finish the current code until the call stack is empty, run every microtask (promise callbacks), let the browser paint if it's time, then take the next task (a timer, a click) and repeat.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Predict the output, then check it in a live example: console.log("a"); setTimeout(() => console.log("b"), 0); Promise.resolve().then(() => console.log("c")).then(() => console.log("d")); console.log("e");

02

Write code that prints sync, micro, task in that order, using one of each mechanism, with the lines written in the order task, micro, sync.

Explain it without notes

01

Explain the event loop: call stack, task queue, microtask queue and rendering.

02

What is the difference between a task and a microtask? Name examples of each.

03

Predict and explain: setTimeout(() => log(1)); Promise.resolve().then(() => log(2)); log(3);.

04

How can microtasks freeze a page, and why can't the user see DOM changes during a long task?

Each task gets its own microtasks

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

sync
microtask 1
microtask added by microtask 1
timer 1
microtask from timer 1
timer 2