Bitpath

Lesson 1 · Unit 03

The event loop

The call stack, tasks and microtasks, and why a promise beats a zero timeout

13 exercisesabout 3 min

What you practise

  • The call stack, tasks and microtasks, why a resolved promise runs before a zero timeout
  • Output order predicted and run

Try a question from this lesson

Pick one

The timer is set first, with a delay of 0 ms. In what order do the three lines print?

JavaScript
setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() =>
  console.log("promise"));
console.log("sync");
Hint

Nothing that was scheduled can run until the code that is running now has finished.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Two queues

Timers, clicks and network responses queue up as tasks. Promise callbacks queue up as microtasks.

The loop runs one task to the end, then every microtask, then the next task. A microtask never waits behind a task.

Node and browsers agree on this order for every case in this lesson.

call stack   what is running now
microtasks   promise callbacks, await
tasks        timers, clicks, network

Concept

The call stack

The call stack is the list of functions that have started and not yet returned. A call pushes one on. A return pops it off.

A task is finished when the stack is empty. Until then nothing else on the thread can run: no other task, no microtask, no paint.

function a() { b(); }
function b() { c(); }
function c() { /* running */ }
a();

stack while c runs (top first)
  c
  b
  a

10 more exercises in the app

  • 3× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× match the pairs
  • 1× order the lines
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy