Sikau

JavaScript · Day 51 · about 20 min

Why code waits

The restaurant order.

A restaurant, not a queue

In a busy restaurant, the waiter doesn't stand frozen at the kitchen door until your dal bhat is ready. They take the order, serve other tables, and bring your food when it's done. JavaScript works the same way — this is asynchronous code.

Synchronous vs asynchronous

Synchronous code runs one line after another; each waits for the one before. Asynchronous code starts a slow job (a timer, a download) and carries on; a callback runs when the job finishes.

console.log("1. Take order");

setTimeout(() => {
  console.log("3. Dal bhat served 🍛");
}, 500);

console.log("2. Serve other tables");

Why not just wait?: A web page has one waiter. If it froze while waiting for a download, buttons wouldn't click and the page couldn't scroll. Async code keeps the page responsive.

The rest of this lesson

  • Callbacks in a rowexplain
  • One thread, a queue of jobsexplain
  • Predict the orderpredict
  • The event looporder
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript