Happy file JavaScript asynchronous programming

JavaScript asynchronous programming
 

Table of contents

JavaScript asynchronous programming

The concept of asynchronous

When to use asynchronous programming

Callback

Example

Example

Example

Asynchronous AJAX

Example

Example


 

 

The concept of asynchronous

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

In the traditional single-threaded programming we learn, the running of the program is synchronous (synchronous does not mean that all steps run at the same time, but means that the steps are executed sequentially in a control flow sequence). The concept of asynchronous is a concept that does not guarantee synchronization. That is to say, the execution of an asynchronous process will no longer have a sequential relationship with the original sequence.

The simple understanding is: synchronization is executed in the order of your code, asynchronous execution is not in the order of the code, and asynchronous execution is more efficient.

The above is an explanation of the concept of asynchronous. Next, let’s explain asynchronous in a simple way: Asynchronous is to launch a sub-thread from the main thread to complete the task.

 

When to use asynchronous programming

In front-end programming (even the back-end is sometimes like this), when we deal with some short and fast operations, such as calculating the result of 1 + 1, it can often be completed in the main thread. As a thread, the main thread cannot accept multiple requests at the same time. Therefore, when an event does not end, the interface will not be able to handle other requests.

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

In order to avoid this situation, we often use child threads to complete things that may take long enough to be noticed by the user, such as reading a large file or making a network request. Because the child thread is independent of the main thread, even if it is blocked, it will not affect the operation of the main thread. But the sub-thread has a limitation: once it is launched, it will lose synchronization with the main thread. We cannot determine its end. If we need to process something after the end, such as processing information from the server, we cannot merge it into the main thread. Go in.

In order to solve this problem, asynchronous operation functions in JavaScript often use callback functions to process the results of asynchronous tasks.

Callback

The callback function is a function that tells it when we start an asynchronous task: what to do after you complete the task. In this way, the main thread hardly needs to care about the status of the asynchronous task, and it will start and end by itself.

Example

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

 

The setTimeout in this program 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 child thread will be generated, and the child thread will Wait for 3 seconds, then execute the callback function "print" and output "RUNOOB!" on the command line.

Of course, JavaScript syntax is very friendly. We don’t have to define a separate function print. We often write the above program as:

Example

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

 

**Note:** Since setTimeout will wait for 3 seconds in the child thread, the main thread does not stop after the setTimeout function is executed, so:

Example

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

 

The execution result of this program is:


RUNOOB-1!
RUNOOB-2!

Asynchronous AJAX

In addition to the setTimeout function, asynchronous callbacks are widely used in AJAX programming. For details about AJAX, please see: https://www.kxdang.com/topic//ajax/ajax-tutorial.html

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

Example

var xhr = new XMLHttpRequest();
 
xhr.onload = function () {
    // 输出接收到的文字数据
    document.getElementById("demo").innerHTML=xhr.responseText;
}
 
xhr.onerror = function () {
    document.getElementById("demo").innerHTML="请求出错";
}
 
// 发送异步 GET 请求
xhr.open("GET", "https://www.kxdang.com/topic//try/ajax/ajax_info.txt", true);
xhr.send();

 

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

Example

$.get("https://www.kxdang.com/topic//try/ajax/demo_test.php",function(data,status){
    alert("数据: " + data + "\n状态: " + status);
});

 

Guess you like

Origin blog.csdn.net/2301_76147196/article/details/129383445