Easy Tutorial
❮ Js Chrome Js Obj String ❯

JavaScript Asynchronous Programming

Concept of Asynchronous

Asynchronous (async) is the 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 control flow sequence). 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 execution follows the order of your code, while asynchronous execution does not follow the code order and is more efficient.

The above is an explanation of the concept of asynchronous. Next, let's explain asynchronous in a more straightforward way: asynchronous means 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 completed 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.

Suppose there is a button, and if we set its onclick event to an infinite loop, then when the button is pressed, the entire web page will become unresponsive.

To avoid this situation, we often use sub-threads to handle tasks that may 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 does not 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-processing is needed after completion, such as handling information from the server, it cannot be merged back into the main thread.

To solve this problem, 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 after the completion of an asynchronous task. This way, the main thread hardly needs to care about the state 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 long 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, which waits for 3 seconds and then executes the callback function "print", outputting "tutorialpro!" in the command line.

Of course, JavaScript syntax is very friendly, and 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, so:

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 more details on AJAX, please refer to: 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 received text data
    document.getElementById("demo").innerHTML=xhr.responseText;
}

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

// Send 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 and when it 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 Chrome Js Obj String ❯