Async JavaScript

Handle delayed work without blocking the page.

JavaScript is designed to execute code one line at a time. This is known as synchronous execution. Some tasks take time, such as loading data, downloading images, reading files, or waiting for user input.

Asynchronous JavaScript allows time-consuming tasks to run in the background while the rest of the program continues to execute.

Why Is Asynchronous JavaScript Important?

Without asynchronous programming, a page could freeze while waiting for data. With asynchronous programming, the page remains responsive while work happens in the background.

Synchronous vs Asynchronous Code

Synchronous Example

javascript
console.log("Step 1");

console.log("Step 2");

console.log("Step 3");

Output:

javascript
Step 1
Step 2
Step 3

Asynchronous Example

javascript
console.log("Start");

setTimeout(() => {
    console.log("Task Complete");
}, 2000);

console.log("End");

Output:

javascript
Start
End
Task Complete

The setTimeout() Function

javascript
setTimeout(() => {
    console.log("Hello after 3 seconds");
}, 3000);

The number 3000 represents milliseconds, which equals 3 seconds.

The setInterval() Function

javascript
setInterval(() => {
    console.log("Running...");
}, 1000);

The message appears every second until the interval is stopped.

Callback Functions

A callback is a function passed to another function and executed later.

javascript
function fetchData(callback) {
    setTimeout(() => {
        console.log("Data Loaded");
        callback();
    }, 2000);
}

fetchData(() => {
    console.log("Processing Data");
});

Output:

javascript
Data Loaded
Processing Data

Real-World Example

javascript
console.log("Loading Weather Data...");

setTimeout(() => {
    console.log("Weather Data Received");
}, 3000);

This allows the user to continue interacting with the website while data loads.

How JavaScript Handles Asynchronous Tasks

  • The Call Stack
  • Browser APIs
  • The Callback Queue
  • The Event Loop

Summary

Asynchronous JavaScript allows long-running tasks to execute in the background while the rest of the program continues to run. setTimeout(), setInterval(), callbacks, and the event loop help developers build responsive applications.

Let's learn with DevBrainBox AI