Track 02 · Lesson 10 of 17Inside the browser
- 01Events and bubbling
- 02What fires when you click or type
- 03Keyboard, input and focus events
- 04Default actions and preventDefault()
- 05Event delegation
- 06Listener options and cleanup
- 07Custom events
- 08Debounce and throttle
- 09Events in React
- 10The event loop
- 11Don't block the main thread
- 12The rendering pipeline
- 13Core Web Vitals
- 14HTTP caching
- 15Responsive design
- 16SEO basics
- 17Service workers and offline
The event loop
Lesson 10 of 17· 9 min
JavaScript does one thing at a time. Timers, network calls and promises never interrupt it: their callbacks wait in queues until the call stack is empty. Microtasks, like promise callbacks, always run before the next task, like a timer or a click. Guess the output, then step through.
Guess, then step through
Three small programs
Your guess: click the lines in the order you think they’ll print
console.log("A: start");setTimeout(() => {console.log("D: timeout");}, 0);Promise.resolve().then(() => {console.log("C: promise");});console.log("B: end");
Call stack
Browser APIs
Microtask queue
Task queue
Console
(nothing printed yet)
Step 1 of 10
The whole script is the first task. It starts running on the call stack.
The four boxes#
- The call stack is what's running right now. There's only one, which is why JavaScript is "single-threaded".
- Browser APIs do the waiting outside JavaScript: timers, network requests, listening for clicks.
- The microtask queue holds promise callbacks, code after an
await, and anything passed toqueueMicrotask. - The task queue holds timer callbacks, events like clicks, and messages.
The order of play#
- Run the current task until the stack is empty. The first task is your script.
- Run every microtask, including any new ones added along the way.
- Maybe render a frame.
- Take one task from the task queue, and go back to step 1.
That's why setTimeout(fn, 0) doesn't mean "now": it means "after everything that's already queued, and after all the microtasks".
Check yourself