Easy Tutorial
❮ Js Class Intro Jsref Constructor Class ❯

JavaScript Asynchronous Programming

Concept of Asynchronous

Asynchronous (async) is a concept opposite to synchronous (sync).

In traditional single-threaded programming, the execution of the program is synchronous (synchronous does not mean all steps run simultaneously, but rather that steps are executed sequentially in a single control flow). Asynchronous, on the other hand, does not guarantee synchronization, meaning the execution of an asynchronous process is no longer in sequence with the original sequence.

Simply put, synchronous executes your code in order, while asynchronous does not execute in the order of the code, resulting in higher efficiency.

The above is an explanation of the concept of asynchronous. To put it in layman's terms: asynchronous is about launching a sub-thread from the main thread to complete tasks.

When to Use Asynchronous Programming

In front-end programming (and sometimes in the back-end as well), when dealing with short and quick operations, such as calculating the result of 1 + 1, these can often be handled in the main thread. The main thread, being a single thread, cannot handle multiple requests simultaneously. Therefore, when an event is not finished, the interface cannot process other requests.

Consider a button; if we set its onclick event to an infinite loop, pressing this button would make the entire webpage unresponsive.

To avoid such situations, we often use sub-threads to handle tasks that might take long enough to be noticeable by the user, such as reading a large file or making a network request. Since sub-threads are independent of the main thread, even if they get blocked, it won't affect the main thread's operation. However, sub-threads have a limitation: once launched, they lose synchronization with the main thread, and we cannot determine their completion. If post-completion actions are needed, such as processing information from the server, it cannot be merged back into the main thread.

To address this issue, asynchronous functions in JavaScript often use callback functions to handle the results of asynchronous tasks.

Callback Functions

A callback function is a function that is told to execute upon the completion of an asynchronous task. This way, the main thread hardly needs to care about the status of the asynchronous task; it will handle everything from start to finish.

Example

function print() {
    document.getElementById("demo").innerHTML="tutorialpro!";
}
setTimeout(print, 3000);

In this program, setTimeout is a process that takes a longer time (3 seconds). Its first parameter is a callback function, and the second parameter is the number of milliseconds. After this function is executed, a sub-thread is created that waits for 3 seconds and then executes the callback function "print", outputting "tutorialpro!" in the command line.

JavaScript syntax is very user-friendly; we don't need to define a separate function print; we often write the above program as:

Example

setTimeout(function () {
    document.getElementById("demo").innerHTML="tutorialpro!";
}, 3000);

Note: Since setTimeout waits for 3 seconds in a sub-thread, the main thread does not stop after setTimeout is executed. Therefore:

Example

setTimeout(function () {
    document.getElementById("demo1").innerHTML="tutorialpro-1!";
}, 3000);
document.getElementById("demo2").innerHTML="tutorialpro-2!";

The execution result of this program is:

tutorialpro-1!
tutorialpro-2!

Asynchronous AJAX

Besides the setTimeout function, asynchronous callbacks are widely used in AJAX programming. For detailed information about AJAX, see: https://www.tutorialpro.org/ajax/ajax-tutorial.html

XMLHttpRequest is often used to request XML or JSON data from a remote server. A standard XMLHttpRequest object usually includes multiple callbacks:

Example

var xhr = new XMLHttpRequest();

xhr.onload = function () {
    // Output the received text data
    document.getElementById("demo").innerHTML=xhr.responseText;
}

xhr.onerror = function () {
    document.getElementById("demo").innerHTML="Request Error";
}

// Send an asynchronous GET request
xhr.open("GET", "https://www.tutorialpro.org/try/ajax/ajax_info.txt", true);
xhr.send();

The onload and onerror properties of XMLHttpRequest are functions that are called when the request is successful or fails, respectively. If you use the full jQuery library, you can also use asynchronous AJAX more elegantly:

Example

$.get("https://www.tutorialpro.org/try/ajax/demo_test.php",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
});
❮ Js Class Intro Jsref Constructor Class ❯