Command Palette

Search for a command to run...

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

click() from code vs a real click

With btn.click() the stack is never empty between listeners (our script is still running), so microtasks wait until the end. Now click the button yourself: you get listener 1, microtask 1, listener 2, microtask 2, because the browser calls each listener from an empty stack.

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?

click() from code vs a real click

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

listener 1
listener 2
after btn.click()
microtask 1
microtask 2