Asynchronous programming lets you perform tasks (like fetching data or waiting for user input) without blocking the rest of your code. This is crucial for building fast, responsive web apps.
// Synchronous
console.log("A");
console.log("B");
// Output: A B
// Asynchronous
console.log("A");
setTimeout(() => { console.log("B"); }, 1000);
console.log("C");
// Output: A C B
setTimeout, event handlers)
console.log("Start");
setTimeout(() => { console.log("Done"); }, 1500);
console.log("End");
// Output: Start End Done
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
wait(1000).then(() => console.log("1 second passed"));
async function main() {
await wait(500);
console.log("Half a second later!");
}
main();
setTimeout, Promises, and async/await to schedule and coordinate tasks in your own scripts!