~/hackweb.dev
Async JavaScript
Quiz
...

Async JavaScript

advanced · updated Tue Sep 08 2026Contribute

Understand the event loop, callbacks, and asynchronous programming.

Async JavaScript

JavaScript handles asynchronous operations using the event loop, callbacks, and modern async patterns.

Synchronous vs Asynchronous

Synchronous code blocks each line. Async code runs in the background.

console.log("Start");
setTimeout(() => console.log("Async"), 1000);
console.log("End");
// Output: Start, End, Async

Remember: Without async, the entire UI freezes during long operations.

The Call Stack

JavaScript executes one function at a time via a stack.

function third() { console.log("Third"); }
function second() { third(); console.log("Second"); }
function first() { second(); console.log("First"); }
first();
// Output: Third, Second, First

The Event Loop

  1. Execute all synchronous code
  2. Push async callbacks to the message queue
  3. When the stack is empty, run the next queue callback
console.log("1");
setTimeout(() => console.log("2"), 0);
console.log("3");
// Output: 1, 3, 2

Callbacks

A function passed as an argument, executed later.

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

fetchData((result) => {
  console.log(result); // "Data received"
});

setTimeout and setInterval

// One-time delay
setTimeout(() => console.log("Hello"), 2000);

// Repeating interval
let count = 0;
let id = setInterval(() => {
  console.log(`Count: ${count++}`);
  if (count >= 5) clearInterval(id);
}, 1000);

Tip: Always clear setInterval when done to prevent memory leaks.

Callback Hell

Chaining callbacks creates deeply nested, hard-to-read code.

step1((err, result1) => {
  step2(result1, (err, result2) => {
    step3(result2, (err, result3) => {
      console.log(result3);
    });
  });
});

This is why Promises and async/await exist — they flatten the nesting.

Best Practices

  • Avoid deep nesting — Use Promises or async/await
  • Always handle errors — Pass error as first callback argument
  • Clear intervals — Prevent memory leaks
  • Keep callbacks small — One thing per callback

Common Mistakes

  • Callback hell — Nesting too deep
  • Ignoring errors — Not passing error in callbacks
  • Assuming order — Async callbacks may run out of order
  • Forgetting to clear timers — Memory leaks