Some things take time: loading data from a server, reading a file, waiting for a timer, waiting for the user to click. The question is: what does the program do while it waits?
Synchronous code
Synchronous code runs line by line, and each line waits for the previous one to finish.
console.log("1. Start");
console.log("2. Middle");
console.log("3. End");
If one step were very slow, everything behind it would wait, and the page would freeze, because JavaScript has a single main thread.
function slowTask() {
const start = Date.now();
while (Date.now() - start < 300) { /* busy wait for 300 ms */ }
}
console.log("before");
slowTask(); // nothing else can happen for 300 ms
console.log("after");
Asynchronous code
Asynchronous code starts a slow job and carries on. When the job finishes, the result is delivered later, through a callback, a promise or await.
console.log("1. Order the coffee");
setTimeout(() => {
console.log("3. Coffee is ready");
}, 500);
console.log("2. Read a book while waiting");
The output order is 1, 2, 3. The timer does not block: JavaScript moves on and comes back when the 500 ms are over.
A restaurant analogy
- Synchronous: a waiter takes your order, goes to the kitchen, stands there until the food is ready, then serves it. Nobody else is served meanwhile.
- Asynchronous: the waiter takes your order, gives it to the kitchen and serves other tables. When the kitchen is done, the waiter brings the dish.
The browser does the waiting (the timer, the network request) outside your JavaScript, and puts your code back in the queue when the result is ready.
What is asynchronous in the browser?
- Timers:
setTimeout,setInterval - Events: clicks, key presses (code runs when they happen)
- Network requests:
fetch() - Reading files, geolocation and many other Web APIs
- Promises and
async/await
Why it matters
- The page stays responsive while data loads.
- You must not expect the result immediately.
let result;
setTimeout(() => { result = "data arrived"; }, 100);
console.log(result); // → undefined (the timer has not finished yet)
Beginners often try to use a value before it exists. The tools in this chapter solve that: callbacks, promises and async/await.