🔟 Asynchronous JavaScript

1. Synchronous vs Asynchronous

✅ Synchronous (Blocking)

Code runs line by line, one after another.

console.log("Start");
console.log("Middle");
console.log("End");

👉 Output:

Start
Middle
End

Everything waits for the previous line to finish.


⚡ Asynchronous (Non-blocking)

Some tasks take time (API calls, timers). JS sends them to the background and continues execution.

console.log("Start");setTimeout(() => {
console.log("Middle");
}, 2000);console.log("End");

👉 Output:

Start
End
Middle

👉 JS doesn’t wait for setTimeout.


2. setTimeout()

Runs code once after a delay

setTimeout(() => {
console.log("Hello after 2 seconds");
}, 2000);

📌 2000 = milliseconds (2 seconds)


3. setInterval()

Runs code again and again at intervals

setInterval(() => {
console.log("Running every 1 second");
}, 1000);

👉 Stops only when cleared:

let id = setInterval(() => {
console.log("Hello");
}, 1000);clearInterval(id);

4. Callbacks

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

function greet(name, callback) {
console.log("Hi " + name);
callback();
}function sayBye() {
console.log("Bye!");
}greet("Aditya", sayBye);

❌ Callback Problem (Callback Hell)

setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3");
}, 1000);
}, 1000);
}, 1000);

👉 Hard to read 😵


5. Promises

Promises solve callback problems.

👉 A Promise has 3 states:

  • Pending
  • Resolved (success)
  • Rejected (error)

Example:

let promise = new Promise((resolve, reject) => {
let success = true; if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
});

Using Promise:

promise
.then(result => console.log(result))
.catch(error => console.log(error));

6. async / await (Modern Way)

Cleaner way to use Promises.


Example:

function getData() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
}async function fetchData() {
let result = await getData();
console.log(result);
}fetchData();

👉 await pauses function until result comes.


🌐 Practice: API Data Fetch

Using fetch + then()

fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));

Using async/await (BEST WAY)

async function getPosts() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/posts");
let data = await response.json();
console.log(data);
} catch (error) {
console.log("Error:", error);
}
}getPosts();

🧠 Simple Analogy

  • Synchronous = One worker doing tasks one by one
  • Asynchronous = Multiple workers handling tasks in background

🚀 Practice Tasks (Important)

Try these:

  1. Print numbers 1–5 using setTimeout
  2. Create a digital clock using setInterval
  3. Fetch user data from API and display in HTML
  4. Convert callback code into Promise
  5. Convert Promise into async/await