AI Hints
Home›JavaScript Tutorial›Asynchronous Basics
JavaScript · Lesson 79 of 138

Synchronous and Asynchronous

Waiting without blocking.

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

So far, every line ran one after another, each waiting for the last. That's synchronous code. But some jobs take time, like downloading data or reading a big file. If JavaScript froze while waiting, your page would lock up. So it can start a slow job, carry on, and come back when the job is done. That's asynchronous code.

Synchronous and Asynchronous
From the video: Synchronous and Asynchronous
  • Line by line: synchronous
  • Some jobs are slow
  • Start, carry on, come back

Two ways to wait

Think of a restaurant. A synchronous waiter takes one order, stands by the kitchen until the food is ready, and only then serves the next table. An asynchronous waiter takes an order, passes it to the kitchen, and keeps serving other tables. When the food is ready, they bring it over. JavaScript works like the second waiter.

Synchronous

  • One job at a time
  • Waits for each one
  • Everything else stops

Asynchronous

  • Starts the slow job
  • Keeps working
  • Handles the result later

Where you meet async

Asynchronous code shows up whenever something outside your program is involved. Fetching data from a server. Reading and writing files. Timers. Waiting for a user to click. JavaScript has one main thread, so it uses async code to stay responsive.

keyvalue
Networkfetch data
Filesread and write
Timerswait, then run
Eventsclicks, key presses

Summary

Synchronous code waits for each step. Asynchronous code starts slow jobs and keeps going. Next, the simplest async tool, set timeout.

Key takeaways
  • Sync: one at a time
  • Async: don't block
  • One main thread
Next up: setTimeout — run code later