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.
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.
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)
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 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!
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();
Next you’ll learn how to use CSS Variables to make your styles dynamic and powerful.