Asynchronous JavaScript

Asynchronous JavaScript is a way of writing code that allows a long-running task to start and then lets the rest of your program continue to run without waiting for that task to finish.

Synchronous vs. Asynchronous Execution

Executes line by line, one at a time. If a function takes a long time to complete, the entire program freezes and waits for it. Think of it like a single-lane road; traffic can only move forward after the car in front of it moves. 🚗➡️🚗➡️🚗

For Example:

console.log("First task");
// This could be a very slow function that blocks everything.
slowFunction();
console.log("Third task"); // This line has to wait for slowFunction() to finish.

A common example is using setTimeout, which waits for a specified time before executing a function.

console.log("First task");

setTimeout(() => {
  console.log("Second task (after 2 seconds)");
}, 2000); // Starts a 2-second timer but doesn't wait.

console.log("Third task"); // This line runs immediately, before the timer finishes.

Output:

  1. First task
  2. Third task
  3. Second task (after 2 seconds)

Here’s a quick summary:

So, while asynchronous operations are often used for tasks that are expected to take time (like network requests or timers), the defining characteristic is the ability to perform other operations while waiting, not the wait time itself.