Errors and async · Lesson 35 of 45
Timers and the event loop
setTimeout, and why code doesn't always run in the order you expect.
JavaScript does one thing at a time (single-threaded). Slow things (a timer, a server request) don't block the code: they're registered, the code carries on, and when they finish their callback waits in a queue. The event loop runs queued work once the current code has finished.
- ▶console.log("1: start")
- 2setTimeout(() => {
- 3 console.log("3: timeout")
- 4}, 0)
- 5Promise.resolve().then(() => {
- 6 console.log("2: promise")
- 7})
- 8console.log("1b: end")
Variables
| queue | [] |
Output
Follow the order: normal code, then promises, then timers.
Call stack: code running now
Microtasks: promises and await
Macrotasks: setTimeout and events
The event loop empties the stack, then all microtasks, then one macrotask, and repeats.
let n = 0
const id = setInterval(() => {
n++
console.log("tick", n)
if (n === 3) clearInterval(id)
}, 200)
setTimeout(() => console.log("after 1 second"), 1000)What's the output?
setTimeout(() => console.log("B"), 0)
console.log("A")What will this code print?
What's the output?
setTimeout(() => console.log("timer"), 0)
Promise.resolve().then(() => console.log("promise"))
console.log("sync")What will this code print?
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.