AI Hints
Home›JavaScript Tutorial›Async Practice
JavaScript · Lesson 89 of 138

The Event Loop

How async really works.

⏱ 2 min read▶ Video at 1:47:02🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

JavaScript runs on one thread. It can only do one thing at a time. So how does it wait for timers and network requests while still running code? The answer is the event loop.

The Event Loop
From the video: The Event Loop
  • One thread
  • One thing at a time
  • So how does it wait?

The loop

First, the call stack runs your normal code, line by line. Slow jobs like timers and fetch are handed to the browser or Node, which wait for them. When a job finishes, its callback joins a queue. And whenever the stack is empty, the event loop takes the next callback from the queue, and runs it.

  1. Call stack runs code
  2. Slow jobs handed off
  3. Callbacks join the queue
  4. Loop runs the next one

Who goes first?

Here are three kinds of code. Normal code runs first, so one and four. Promise callbacks go in a special queue, called the microtask queue, which runs before timers. So three comes next. Then the timer, two, last of all. Run it.

app.jsjavascript
console.log("1. normal code");

setTimeout(() => console.log("2. timer"), 0);

Promise.resolve().then(() => console.log("3. promise"));

console.log("4. normal code");
Output
1. normal code
4. normal code
3. promise
2. timer

Summary

The event loop runs queued callbacks whenever the call stack is empty. Normal code first, then promise callbacks, then timers. Next, a quick quiz on async JavaScript.

Key takeaways
  • One thread
  • Stack, then queues
  • Promises before timers
Next up: Async Quiz — test yourself