# Asynchronous Fundamentals

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Async Concepts
Source: https://www.devtutorials.ai/learn/javascript/async/asynchronous-fundamentals

> What asynchronous code is and why JavaScript needs it, sync vs async behaviour, callbacks after a task and with events, callback hell, setTimeout, setInterval and how to cancel them, and the event loop with its microtask and macrotask queues.

## What Is Asynchronous Code?

**Synchronous** = one line at a time; each line finishes before the next starts.
**Asynchronous (async)** = start a slow task now, keep going, and finish it **later**.

- Timers, downloads and clicks are all async.
- A **callback** is the function that runs when the task is done.
- The **event loop** decides what runs next.

**Simple lesson:** JavaScript never waits. It starts the slow task, moves on, and comes back when the result is ready.

### A Real-World Example

At a food counter you order, get a token, and step aside.
The next customer orders while your food cooks; your number is called when it is ready.
A shop page works the same way: it asks for products, keeps responding to clicks, and shows the list when it arrives.

<figure className="ts-fig">
  <svg viewBox="0 0 560 180" role="img" aria-label="A call stack box runs plain lines. A timer waits in a queue box. When the stack is empty, the event loop arrow moves the timer callback onto the stack." width="100%">
    <rect x="0" y="0" width="560" height="180" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="30" y="30" width="160" height="110" rx="10" fill="#eff6ff" stroke="#2563eb" />
    <text x="110" y="52" textAnchor="middle" fontSize="12" fill="#1e40af">Call stack (now)</text>
    <text x="110" y="80" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#1e40af">log("1. Order")</text>
    <text x="110" y="100" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#1e40af">log("2. Next")</text>
    <rect x="370" y="30" width="160" height="110" rx="10" fill="#fef3c7" stroke="#d97706" />
    <text x="450" y="52" textAnchor="middle" fontSize="12" fill="#92400e">Task queue (later)</text>
    <rect x="390" y="70" width="120" height="28" rx="6" fill="#fde68a" stroke="#d97706"><animate attributeName="x" values="390;390;50;50" keyTimes="0;0.5;0.8;1" dur="4s" repeatCount="indefinite" /></rect>
    <text x="450" y="89" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#92400e">3. Food ready<animate attributeName="x" values="450;450;110;110" keyTimes="0;0.5;0.8;1" dur="4s" repeatCount="indefinite" /></text>
    <path d="M370 120 C 300 170, 260 170, 190 120" fill="none" stroke="#16a34a" strokeWidth="2" strokeDasharray="5 4"><animate attributeName="stroke-dashoffset" values="40;0" dur="1.2s" repeatCount="indefinite" /></path>
    <text x="280" y="170" textAnchor="middle" fontSize="12" fill="#166534">event loop: when the stack is empty, run the next task</text>
  </svg>
  <figcaption>Plain code runs first. Waiting callbacks run when the stack is free.</figcaption>
</figure>

Boxes stop collecting output at their last line. Many boxes here end with `await new Promise((resolve) => setTimeout(resolve, 100));`, which keeps the box open so timers can run. The next lesson explains it.

## What You Will Learn

1. What async means, and why JavaScript needs it.
2. Callbacks: after a task, and for events.
3. Callback hell.
4. Timers: `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval`.
5. The event loop, microtasks and macrotasks, and how to predict the order.

## Asynchronous Basics

### What async means

- **Synchronous shop:** you wait at the counter, and nobody behind you can order.
- **Asynchronous shop:** you take a token and step aside; others order while you wait.

### Why JavaScript needs async code

JavaScript runs on one **thread** (one line of work at a time). The same thread draws the page, so waiting would freeze it. Here a busy loop delays a timer:

```js runnable title="A timer cannot run while the thread is busy with other work"
const start = performance.now();
let ranAfter = 0;

setTimeout(() => {
  ranAfter = performance.now() - start;
}, 10);

// Keep the thread busy for 200 milliseconds.
while (performance.now() - start < 200) {}

await new Promise((resolve) => setTimeout(resolve, 100));
console.log("The timer asked to run after 10 ms.");
console.log("It actually waited at least 200 ms:", ranAfter >= 200);
```

Expected output:

```text
The timer asked to run after 10 ms.
It actually waited at least 200 ms: true
```

`performance.now()` is a clock for measuring time. A timer's delay is only a **minimum**.

### Sync vs async behaviour

Watch the print order. `setTimeout` returns at once, so line 2 prints before the timer's line 3.

```js runnable title="The timer line is written second, but it prints last"
console.log("1. Order placed");

setTimeout(() => {
  console.log("3. Food is ready");
}, 50);

console.log("2. Next customer, please");

await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
1. Order placed
2. Next customer, please
3. Food is ready
```

### Real use cases (APIs, file uploads, timers)

- **APIs:** asking another computer for data can take milliseconds or seconds.
- **File uploads:** the page must stay usable while a file is sent.
- **Timers:** reminders, countdowns, messages that disappear later.

A real API call (not runnable here; boxes do not reach real websites):

```js
fetch("https://api.example.com/products")
  .then((response) => response.json())
  .then((products) => console.log(products));
```

A pretend upload with a timer:

```js runnable title="A pretend upload finishes later, while other work carries on"
function uploadFile(fileName) {
  console.log(`Uploading ${fileName}...`);
  setTimeout(() => {
    console.log(`${fileName} uploaded.`);
  }, 60);
}

uploadFile("Invoice.pdf");
console.log("You can keep editing while the file uploads.");

await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
Uploading Invoice.pdf...
You can keep editing while the file uploads.
Invoice.pdf uploaded.
```

## Callback Functions

### Passing a function as an argument

**Callback** = a function you pass to another function, so it can call it later. Pass it **without** `()`.

```js runnable title="greet receives a function and decides when to call it"
function greet(name, format) {
  return format(name);
}

function polite(name) {
  return `Good morning, ${name}.`;
}

console.log(greet("Asha", polite));
console.log(greet("Ravi", (name) => `Hi ${name}!`));
```

Expected output:

```text
Good morning, Asha.
Hi Ravi!
```

**Why "callback"?** It is "called back" later, like a shop calling your token number.

### Using callbacks after a task finishes

A slow function cannot `return` a result that does not exist yet. It calls your callback with the result later.

```js runnable title="loadOrder hands the order to a callback when it has arrived"
function loadOrder(orderId, onLoaded) {
  setTimeout(() => {
    const order = { id: orderId, customer: "Meera", total: 420 };
    onLoaded(order);
  }, 40);
}

console.log("Asking for order 5012...");

loadOrder(5012, (order) => {
  console.log(`Order ${order.id} for ${order.customer}: ₹${order.total}`);
});

console.log("Request sent.");

await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
Asking for order 5012...
Request sent.
Order 5012 for Meera: ₹420
```

### Callbacks with events

**Event** = something that happens: a click, a key press. `addEventListener` calls your callback **every** time. Click the button:

```dom runnable title="A callback that runs every time the button is clicked"
<button id="place-order">Place order</button>
<p id="status">No orders yet.</p>
<script>
  let ordersPlaced = 0;
  document.querySelector("#place-order").addEventListener("click", () => {
    ordersPlaced += 1;
    document.querySelector("#status").textContent = `Orders placed: ${ordersPlaced}`;
    console.log("click callback ran, ordersPlaced =", ordersPlaced);
  });
  console.log("The listener is ready. Click the button.");
</script>
```

Without a page, an `EventTarget` does the same. `dispatchEvent` sends an event out:

```js runnable title="The same listener callback runs once for each event"
const doorbell = new EventTarget();

doorbell.addEventListener("ring", () => {
  console.log("Someone is at the door.");
});

console.log("Listener added.");
doorbell.dispatchEvent(new Event("ring"));
doorbell.dispatchEvent(new Event("ring"));
console.log("Two rings handled.");
```

Expected output:

```text
Listener added.
Someone is at the door.
Someone is at the door.
Two rings handled.
```

### Callback hell

When each step needs the last one's result, callbacks nest deeper and deeper. It works, but it is hard to read and to handle errors.

```js runnable title="Three steps, each one nested inside the last"
function login(user, callback) {
  setTimeout(() => callback({ user, token: "abc123" }), 10);
}
function getOrders(session, callback) {
  setTimeout(() => callback([5012, 5013]), 10);
}
function getOrderTotal(orderId, callback) {
  setTimeout(() => callback(orderId === 5012 ? 420 : 180), 10);
}

login("Asha", (session) => {
  console.log("Logged in as", session.user);
  getOrders(session, (orderIds) => {
    console.log("Orders:", orderIds.join(", "));
    getOrderTotal(orderIds[0], (total) => {
      console.log(`Order ${orderIds[0]} total: ₹${total}`);
    });
  });
});

await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
Logged in as Asha
Orders: 5012, 5013
Order 5012 total: ₹420
```

Callback hell is why promises and `async`/`await` exist. **Promises and Async/Await** runs the same steps with no nesting.

## Timing Events

### Timer-based async work

A timer says "run this after N **milliseconds**" (1000 ms = 1 second). Each timer returns a **timer id**, used to cancel it.

```js runnable title="Each timer gets its own id, and the id is what cancels it"
const firstId = setTimeout(() => console.log("first timer ran"), 30);
const secondId = setTimeout(() => console.log("second timer ran"), 30);

console.log("each id is different:", firstId !== secondId);
clearTimeout(firstId);

await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
each id is different: true
second timer ran
```

### `setTimeout()`

Runs a callback **once**, after at least the delay. Timers run in order of when they are **due**, not when they were written.

```js runnable title="Two reminders, and the shorter delay runs first"
setTimeout(() => {
  console.log("Reminder: team meeting at 3 pm");
}, 60);

setTimeout(() => {
  console.log("Reminder: reply to Ravi's email");
}, 20);

console.log("Reminders are scheduled.");

await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
Reminders are scheduled.
Reminder: reply to Ravi's email
Reminder: team meeting at 3 pm
```

### `clearTimeout()`

Cancels a timer that has not run yet, using its id.

```js runnable title="The session warning is cancelled because the user clicked in time"
const warningId = setTimeout(() => {
  console.log("Your session is about to expire.");
}, 50);

console.log("Warning scheduled.");

// The user clicks something, so the warning is no longer needed.
clearTimeout(warningId);
console.log("User was active, warning cancelled.");

await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
Warning scheduled.
User was active, warning cancelled.
```

### `setInterval()`

Runs a callback **again and again**, every delay, until stopped.

```js runnable title="A countdown that ticks every 20 milliseconds"
let secondsLeft = 3;

const countdownId = setInterval(() => {
  console.log("Seconds left:", secondsLeft);
  secondsLeft -= 1;

  if (secondsLeft === 0) {
    clearInterval(countdownId);
    console.log("Lift off!");
  }
}, 20);

await new Promise((resolve) => setTimeout(resolve, 150));
```

Expected output:

```text
Seconds left: 3
Seconds left: 2
Seconds left: 1
Lift off!
```

### `clearInterval()`

Stops an interval. Without it, an interval runs as long as the page is open.

```js runnable title="A progress bar that stops at 100 percent"
let progress = 0;

const progressId = setInterval(() => {
  progress += 25;
  console.log(`Progress: ${progress}%`);

  if (progress >= 100) {
    clearInterval(progressId);
    console.log("Interval stopped.");
  }
}, 15);

await new Promise((resolve) => setTimeout(resolve, 150));
console.log("Final progress:", progress);
```

Expected output:

```text
Progress: 25%
Progress: 50%
Progress: 75%
Progress: 100%
Interval stopped.
Final progress: 100
```

Always store an interval's id, and clear it when the work is done.

### Zero-delay timeout

`setTimeout(fn, 0)` does **not** mean "now". It means "after the current code finishes".

```js runnable title="A 0 ms timer still waits for every plain line to finish"
setTimeout(() => {
  console.log("3. zero-delay timer");
}, 0);

for (let step = 1; step <= 2; step += 1) {
  console.log(`${step}. plain line`);
}

await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
1. plain line
2. plain line
3. zero-delay timer
```

## Event Loop and Task Queue

- **Call stack** = the functions running right now.
- **Queue** = a waiting line: first in, first out.
- **Event loop** = keeps checking "is the stack empty? Then run the next waiting job."

**Why "loop"?** It goes round and round, checking the queues.

### Microtask queue

Small jobs that run as soon as the current code finishes: `.then()` callbacks and `queueMicrotask()`. A **promise** stands for a result that arrives later; `Promise.resolve()` is one that is already done.

```js runnable title="Microtasks run after the plain lines, in the order they were queued"
queueMicrotask(() => console.log("3. first microtask"));
Promise.resolve().then(() => console.log("4. second microtask"));

console.log("1. plain line");
console.log("2. plain line");
```

Expected output:

```text
1. plain line
2. plain line
3. first microtask
4. second microtask
```

### Macrotask queue

Larger jobs, one per turn: timer and event callbacks.

```js runnable title="Timer callbacks wait in the macrotask queue, one after another"
setTimeout(() => console.log("2. first timer"), 0);
setTimeout(() => console.log("3. second timer"), 0);

console.log("1. plain line");

await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
1. plain line
2. first timer
3. second timer
```

| Queue | What goes in it | Examples |
|---|---|---|
| Microtask queue | small jobs that follow the current code | `.then()` callbacks, `queueMicrotask()` |
| Macrotask queue | larger jobs, one per turn of the loop | `setTimeout`, `setInterval`, click events |

### Promise callbacks vs timer callbacks

The timer is queued first, but the promise callback runs first: the loop empties **all** microtasks before **one** macrotask.

```js runnable title="The timer is queued first, but the promise callback runs first"
setTimeout(() => console.log("3. timer callback"), 0);

Promise.resolve().then(() => console.log("2. promise callback"));

console.log("1. plain line");

await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
1. plain line
2. promise callback
3. timer callback
```

Order: all plain code → every microtask → one macrotask → every microtask → ...

### Execution order in async code

1. Run all plain code, top to bottom.
2. Run every microtask, including new ones added on the way.
3. Run **one** macrotask.
4. Go back to step 2.

Predict the order before you run it:

```js runnable title="Plain lines, microtasks and timers, with a microtask added inside a timer"
console.log("A. plain line");

setTimeout(() => {
  console.log("E. first timer");
  Promise.resolve().then(() => console.log("F. microtask added by the first timer"));
}, 0);

setTimeout(() => console.log("G. second timer"), 0);

Promise.resolve().then(() => {
  console.log("C. first microtask");
  queueMicrotask(() => console.log("D. microtask added by a microtask"));
});

console.log("B. plain line");

await new Promise((resolve) => setTimeout(resolve, 100));
```

Expected output:

```text
A. plain line
B. plain line
C. first microtask
D. microtask added by a microtask
E. first timer
F. microtask added by the first timer
G. second timer
```

Sort each line into plain code, microtask or macrotask, and you can predict any async order.

## Async Code on a Web Page

A countdown with `setInterval`, a message that hides itself with `setTimeout`, and a button that cancels the countdown with `clearInterval`.

```js runnable preview="notices" title="A sale countdown with timers"
const box = document.querySelector("#notices");
const line = document.createElement("p");
const stop = document.createElement("button");
stop.textContent = "Stop countdown";
box.append(line, stop);

let secondsLeft = 5;
line.textContent = `Flash sale ends in ${secondsLeft}s`;

const id = setInterval(() => {
  secondsLeft -= 1;
  line.textContent = secondsLeft > 0 ? `Flash sale ends in ${secondsLeft}s` : "Sale over!";
  if (secondsLeft === 0) clearInterval(id);
}, 1000);

stop.addEventListener("click", () => {
  clearInterval(id);
  line.textContent = "Countdown stopped.";
  const toast = document.createElement("p");
  toast.textContent = "This note disappears in 2 seconds.";
  box.append(toast);
  setTimeout(() => toast.remove(), 2000);
});

console.log("Countdown started. This line prints before any tick.");
```

**Easy way to remember:** plain code first, then promises (micro), then timers and clicks (macro).

## TL;DR

- Async code starts now and finishes later; JavaScript never waits.
- Callbacks receive results later; events call them every time.
- `setTimeout`/`setInterval` return ids for `clearTimeout`/`clearInterval`.
- A delay is a minimum; `setTimeout(fn, 0)` still runs after current code.
- Plain code → all microtasks → one macrotask, repeat.

## Try this

In **Promise callbacks vs timer callbacks**, add a second `Promise.resolve().then(...)` line. Both promise callbacks run right after the plain line, in order, and the timer still runs last.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Using a value on the next line after an async call | JavaScript waits | It moves on | The value is still empty |
| `setTimeout(fn, 0)` for "now" | Zero means now | It means after current code | It runs after later lines |
| Not clearing an interval | It stops by itself | It runs forever | Endless messages or requests |
| Cancelling too late or with the wrong id | Any id works | Use the id from that timer | The timer still runs |
| A long loop with a timer waiting | Delays are exact | They are minimums | The timer fires late |
| Nesting every step | That is the only way | Name steps; use promises next | Callback hell |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `doTask(value, callback)` | pass a function for another function to call later |
| `target.addEventListener("click", callback)` | run the callback each time the event happens |
| `const id = setTimeout(callback, ms)` | run the callback once, after at least `ms` milliseconds |
| `clearTimeout(id)` | cancel a timeout that has not run yet |
| `const id = setInterval(callback, ms)` | run the callback every `ms` milliseconds |
| `clearInterval(id)` | stop an interval |
| `setTimeout(callback, 0)` | run the callback after the current code and all microtasks |
| `Promise.resolve().then(callback)` | queue a microtask |
| `queueMicrotask(callback)` | queue a microtask directly |
| plain code → all microtasks → one macrotask | the order the event loop follows |

</div>

## Exercises

## What to Remember

- Async = start now, finish later.
- Callbacks and timers are the basic tools.
- The event loop's order is predictable.

Next: **Promises and Async/Await**. Promises, their states and chaining, and `async`/`await` that read from top to bottom.
