JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Asynchronous


JavaScript is a single-threaded, synchronous language by default. This means it executes one task at a time in order. However, modern applications often need to perform tasks that take time, such as network requests, reading files, timers, or animations. If JavaScript handled these tasks synchronously, the program would freeze until the task was complete.

To solve this, JavaScript uses asynchronous programming. Asynchronous programming allows JavaScript to start a task and continue running other tasks while waiting for the long-running task to complete. This is what makes JavaScript responsive and efficient for real-time applications like chat apps, games, and dashboards.

Synchronous vs Asynchronous

Synchronous Code

console.log("Task 1");
console.log("Task 2");
console.log("Task 3");

Output:

Task 1
Task 2
Task 3

Each statement waits for the previous one to finish before moving forward.

Asynchronous Code

console.log("Task 1");

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

console.log("Task 3");

Output:

Task 1
Task 3
Task 2 (after 2 seconds)
  • setTimeout does not block the program.

  • While waiting, JavaScript moves on to the next task.

How JavaScript Handles Asynchronous Code

JavaScript uses the event loop with the call stack, Web APIs, and callback queue to manage asynchronous tasks.

  1. Call Stack: Where functions are executed.

  2. Web APIs: Handle async tasks like timers, HTTP requests, DOM events.

  3. Callback Queue: Stores completed async tasks waiting to be executed.

  4. Event Loop: Constantly checks if the call stack is empty and moves tasks from the callback queue to the stack.

Simplified Flow

Code starts → Call Stack executes → Async task goes to Web API →  
When done, callback moves to Queue → Event Loop pushes it back to Call Stack

Common Asynchronous Functions in JavaScript

a) setTimeout

Executes a function after a specified time.

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

b) setInterval

Repeats execution after a fixed interval.

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

c) Event Listeners

Event listeners are inherently asynchronous.

document.getElementById("btn").addEventListener("click", () => {
  console.log("Button clicked!");
});

d) Network Requests (AJAX, Fetch)

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

These tasks depend on the browser’s Web API and run asynchronously.

Callbacks in Asynchronous Programming

Before modern features like Promises and async/await, callbacks were the primary way to handle async code.

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

fetchData((data) => {
  console.log(data);
});

Issue: Too many nested callbacks lead to callback hell.

Asynchronous Problems and Solutions

Problem: Callback Hell

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

This pyramid structure is hard to maintain.

Solution: Promises and Async/Await

  • Promises flatten callbacks into a chain (.then() and .catch()).

  • Async/Await allows writing asynchronous code that looks synchronous.

(We won’t expand here since you already have separate tutorials for them.)

Real-World Examples of Asynchronous Code

Example 1: Loading Data Without Blocking

console.log("Fetching user data...");

setTimeout(() => {
  console.log("User data received");
}, 3000);

console.log("Program continues running...");

The program doesn’t freeze while waiting for user data.

Example 2: Animation

let count = 0;

let interval = setInterval(() => {
  count++;
  console.log("Frame " + count);

  if (count === 5) {
    clearInterval(interval);
    console.log("Animation stopped");
  }
}, 1000);

This simulates an animation loop using asynchronous intervals.

Example 3: Event-Driven Asynchrony

document.addEventListener("keydown", (event) => {
  console.log("Key pressed:", event.key);
});

The program doesn’t wait for a key press—it continues running other tasks.

Best Practices for Asynchronous Programming

  1. Understand the Event Loop – Know how JavaScript schedules tasks.

  2. Avoid Blocking Code – Don’t use heavy loops or synchronous requests.

  3. Prefer Promises or Async/Await – They make async code easier to read than callbacks.

  4. Use Error Handling – Always handle failures in async tasks (.catch, try/catch).

  5. Optimize Performance – Use async tasks wisely to keep apps responsive.

Summary of the Tutorial

  • JavaScript is single-threaded but handles asynchronous tasks using the event loop.

  • Asynchronous programming allows JavaScript to execute long tasks without freezing the program.

  • Common async tools: setTimeout, setInterval, event listeners, and network requests.

  • Callbacks were the original solution but led to callback hell.

  • Modern approaches like Promises and Async/Await solve readability and error-handling issues.

Mastering asynchronous programming is critical for building responsive, interactive, and efficient applications in JavaScript. It is the foundation for handling timers, events, animations, and API requests.


Practice Questions

  1. Write a program that prints "Start", then after 2 seconds prints "Hello from setTimeout", and finally prints "End" immediately after "Start".

  2. Use two setTimeout calls to log "First timeout" after 1 second and "Second timeout" after 3 seconds. Check the order of execution.

  3. Schedule a message "This should not run" after 5 seconds using setTimeout, but cancel it before it executes using clearTimeout().

  4. Write a program that logs "Ping" every second using setInterval. Stop it automatically after 5 executions using clearInterval().

  5. Simulate a process with three steps using nested setTimeout:

    • After 1 second: log "Step 1 complete"

    • After 2 seconds: log "Step 2 complete"

    • After 3 seconds: log "Step 3 complete"

  6. Create a button in HTML. Add an event listener that logs "Button clicked!" when pressed. Demonstrate that the program continues running other code without waiting for the click.

  7. Write the following code and explain why "End" prints before "setTimeout done":

    console.log("Start");
    setTimeout(() => console.log("setTimeout done"), 0);
    console.log("End");
    
  8. Use setInterval to log "Frame 1", "Frame 2", … until "Frame 10". Stop automatically after 10 frames.

  9. Write a function fetchData(callback) that waits 2 seconds and then calls callback("Data received"). Use it to print the message.

  10. Write a script that starts three async tasks using setTimeout:

  • Task A after 1 second

  • Task B after 2 seconds

  • Task C after 0 seconds
    Observe the order in which they are executed and explain why.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top