← Back to JavaScript
34

Async foundations: event loop, call stack and queues

Understand why asynchronous code runs in a specific order so you can avoid timing bugs in UI, promises and timers.

📘 Theory

A minimal mental model

The stack executes, queues wait and the loop coordinates.

  • The call stack contains the functions executing right now.
  • The task queue holds callbacks from timers, events and similar sources.
  • The microtask queue holds promise reactions and `queueMicrotask()` callbacks.
  • The event loop decides when queued work can move back onto the stack.

Common mistakes caused by the wrong mental model

The classic bug is expecting synchronous order where none exists.

1

`setTimeout(..., 0)` does not mean immediate execution. It only means the callback becomes eligible for the task queue after the current synchronous work ends.

2

Resolved promises go to the microtask queue, which is processed before the next regular task from timers.

A practical pattern for async flows

Separate start, asynchronous work and closure clearly.

1

In real code, asynchronous readability improves when you make the phases visible: start state, async operation, success or error, final cleanup.

2

That structure becomes even more important in forms, fetch requests and interface loading states.

🧭 Key visuals

Async flow and the event loop

It clarifies why synchronous code, promises and timers appear in the order they do.

Diagram of the call stack, task queue and microtask queue coordinated by the event loop

🧪 Learn by doing

Example Guided example: predict the order Identify what executes first among synchronous code, a promise and a timer.

🏁 Challenges

Challenge Challenge: add an explicit microtask Use `queueMicrotask()` to reinforce the difference between microtasks and regular tasks.

🧰 Resources

Test

Check your knowledge with a test about JavaScript.

Test for JavaScript

What is this?

I'm Cristian Eslava and I sometimes build websites so both you and I can learn and experiment. culTest

I made this in February 2026 to make learning easier for my students. The idea is to learn web development by practicing and to keep expanding the project with new topics, tests and challenges.

It draws inspiration from MDN, W3Schools, CodePen, Manz and many other web development references. I wanted to combine useful theory, runnable examples, challenges and the testing system I had already built for culTest. culTest

If you liked it, if you didn't, or if you want to get in touch, write to me at cristianeslava@gmail.com