JavaScript 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

How JavaScript Handles Asynchronous Tasks

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

Key Takeaways

  • Asynchronous is an important topic to understand.
  • Start with small examples and practice one step at a time.
  • Use the idea in simple projects so it becomes easier to remember.