Skip to content
Codewilds

Lesson 30 of 34 · Async JavaScript

The JavaScript Event Loop and setTimeout

easy10 XP3 min read

So far every line of your code has run immediately, one after another. But real programs wait all the time: for a timer, a button click, a file or a server response. JavaScript handles all of that without freezing, using a mechanism called the event loop.

Understanding the event loop is the key to everything in this chapter: timers, promises and async/await.

One thread, one thing at a time

JavaScript runs your code on a single thread: it can only do one thing at a time. Function calls are tracked on the call stack: calling a function pushes it on the stack, and returning pops it off.

If JavaScript simply waited for slow operations, the whole page would freeze until they finished. Instead, slow work is handed off to the environment (the browser or Node.js), and JavaScript is told to run a callback later, when the result is ready.

setTimeout: run something later

setTimeout(callback, delay) schedules a callback to run after at least delay milliseconds:

console.log("Brewing potion...");

setTimeout(() => {
  console.log("Potion ready!");
}, 1000);

console.log("Meanwhile, sharpening sword.");

Output:

Brewing potion...
Meanwhile, sharpening sword.
Potion ready!

setTimeout does not pause your program. It registers the callback and returns immediately, so the next line runs right away. A second later, the callback runs.

setTimeout returns an ID, and you can cancel a timer that hasn't fired yet with clearTimeout(id). To repeat something on an interval, use setInterval(callback, ms) and stop it with clearInterval(id).

The event loop

So where does the callback wait? When the timer expires, the callback is placed in the task queue. The event loop follows one simple rule:

When the call stack is empty, take the next callback from the queue and run it.

That has a surprising consequence: even a delay of 0 doesn't run immediately. The callback still has to wait until all the current code has finished:

setTimeout(() => console.log("timeout"), 0);
console.log("sync");
// sync
// timeout

The delay is a minimum, not a guarantee. If the stack is busy with a long loop, every timer waits for it to finish.

Microtasks jump the queue

Promises, which you'll learn about in the next lesson, use a second, higher-priority queue: the microtask queue. After each task, the event loop runs all pending microtasks before taking the next task:

console.log("1: script start");
setTimeout(() => console.log("4: timeout (task)"), 0);
Promise.resolve().then(() => console.log("3: promise (microtask)"));
console.log("2: script end");

The order is: synchronous code first, then microtasks, then tasks (timers).

Common mistakes

  • Treating setTimeout like sleep. Code after setTimeout doesn't wait. Anything that should happen later must go inside the callback.
  • Calling instead of passing. setTimeout(launch(), 1000) runs launch immediately. Pass the function: setTimeout(launch, 1000).
  • var in loops with timers. With var i, all callbacks share one variable and see its final value. With let i, each loop round gets its own i, which is exactly what you want.

Assignment

Write a countdown that prints exactly:

Countdown started
3
2
1
Liftoff!
  • The starter ends with console.log("Countdown started");. Keep that line as the last line of your program. It must still print first.
  • Use setTimeout so that 3, 2, 1 and Liftoff! appear 100 ms apart (after 100, 200, 300 and 400 ms).

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+10 XP

Lesson 30 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.