</>
Skip to content
JavaScript lessons (46/64)

JavaScript — Async

JavaScript does one thing at a time

Single-threaded: one call stack, one statement executing ever. Yet pages download files, run timers and fetch APIs simultaneously. The trick: the environment (browser/Node) handles slow work and queues results back.

console.log("1");
setTimeout(() => console.log("2"), 0);   // "immediate" timer
console.log("3");

// prints: 1, 3, 2   😵

setTimeout hands its callback to the browser's timer; the script finishes; then the callback runs. Zero delay still means "next turn."

The event loop in five lines

  1. Run all synchronous code to completion
  2. Check the task queue — run pending callbacks
  3. Render if needed
  4. Repeat forever

Slow synchronous code blocks everything (frozen UI). That's why slow operations MUST become async.

Era 1: callbacks

Pass a function to run "later":

setTimeout(() => console.log("later"), 1000);

function loadUser(id, callback) {
    setTimeout(() => callback({ id, name: "Ada" }), 500);
}

loadUser(7, user => console.log(user.name));

Callback hell arrives with sequencing:

getUser(u => {
    getPosts(u.id, posts => {
        getComments(posts[0].id, comments => {
            // nesting pyramid of doom…
        });
    });
});

Plus no built-in error channel. Promises fixed both.

Era 2 & 3: promises → async/await

const user = await getUser(7);
const posts = await getPosts(user.id);

Flat, readable, try/catch-able. These get their own lessons next.

Recognizing async everywhere

These all schedule work instead of doing it inline:

APIFires
setTimeout / setIntervalafter delay / repeatedly
addEventListener("click", …)on events
fetch(url)when network answers
.then() chainswhen promises settle

A timing experiment worth running once

console.log("start");

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

for (let i = 0; i < 1e9; i++) {}     // heavy sync work ~1s

console.log("end");
// start → end → timeout

The timer waited for the blocking loop — proof that sync code owns the thread until it's done.

Interview-grade summary: JS runs sync code now; async callbacks are queued and executed only when the stack is empty. await is syntax sugar that pauses your function without blocking the thread.

Mini Practice

  1. Predict-then-run the 1-2-3 timeout demo
  2. Convert nested callbacks into flat sequential calls (still callbacks) — feel the pain motivating promises
  3. Build setInterval clock; stop it after 5 ticks via clearInterval inside
  4. Prove blocking: long loop while an interval "should" fire — note the pile-up

Next: promises →

Related Topics

Frequently Asked Questions about Async

What is Async in JavaScript?

Async is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Async?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Async.

Why is Async important in JavaScript?

Async is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.