JavaScript Async Basics

What Is Asynchronous Code?

JavaScript runs on a single thread — meaning it can only do one thing at a time. Async code allows tasks (like waiting for a server or loading a file) to run in the background without freezing your page.

The Simplest Example: setTimeout()

This delays code without blocking the rest of the script.

console.log("A");
setTimeout(() => console.log("B (after 2 seconds)"), 2000);
console.log("C");

// Output:
// A
// C
// B (after 2 seconds)
  

Callbacks

A callback is a function passed into another function to run later.

function fetchData(callback) {
  setTimeout(() => {
    callback("Data loaded!");
  }, 1000);
}

fetchData((msg) => console.log(msg));
  

Callbacks work, but become messy with many nested steps (callback hell).

Promises

Promises represent a “future value” that will arrive later.

let p = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Success!"), 1000);
});

p.then((msg) => console.log(msg));

// Output: Success!
  

async / await

This is the cleanest and most modern way to write asynchronous code. It looks like normal code but still works asynchronously.

function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function run() {
  console.log("Start");
  await wait(1000);
  console.log("Done after 1 second!");
}

run();
  

Why Async Is Important

What's Next?

Next you’ll learn how to use CSS Variables to make your styles dynamic and powerful.