Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Asynchronous Programming

JavaScript Asynchronous Programming

The Concept of Asynchrony

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

In the traditional single-threaded programming we have studied, programs run synchronously (synchronous does not mean all steps run at the same time, but that steps execute in order within a control flow sequence). The concept of asynchrony means not guaranteeing synchrony; that is, the execution of an asynchronous process no longer has an ordering relationship with the original sequence.

Simply put: synchronous code executes in the order of your code, while asynchronous code does not follow the code order, and asynchronous execution is more efficient.

The above is an explanation of the concept of asynchrony. Next, let us explain asynchrony in plain terms: asynchrony means launching a child thread from the main thread to complete a task.

When to Use Asynchronous Programming

In front-end programming (and sometimes on the back end as well), when handling short, quick operations such as calculating 1 + 1, we can often complete them in the main thread. As a single thread, the main thread cannot accept multiple requests at the same time. Therefore, when an event has not finished, the interface cannot handle other requests.

Now suppose 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.

To avoid this, we often use child threads to perform tasks that may take long enough to be noticed by the user, such as reading a large file or making a network request. Because a child thread is independent of the main thread, even if it blocks, it does not affect the main thread. However, a child thread has one limitation: once launched, it loses synchronization with the main thread, and we cannot determine when it will finish. If we need to handle something after it finishes, such as processing information from the server, we cannot merge it back into the main thread.

To solve this problem, asynchronous operation functions in JavaScript often use callback functions to handle the results of asynchronous tasks.

Callback Function

A callback function is a function that we tell an asynchronous task about when we start it: what to do after you finish this task. In this way, the main thread hardly needs to care about the state of the asynchronous task; it will take care of itself from beginning to end.

Example

function

print

(

)

{

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

"

RUNOOB!

"

;

}

setTimeout

(

print

,

3000

)

;

Try it »

The setTimeout in this program is a process that takes a relatively long time (3 seconds). Its first parameter is a callback function, and its second parameter is a number of milliseconds. After this function executes, a child thread is created; the child thread waits 3 seconds and then executes the callback function "print", outputting "RUNOOB!" on the command line.

Of course, JavaScript syntax is very friendly; we do not need to define a separate function print. We often write the above program as:

Example

setTimeout

(

function

(

)

{

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

"

RUNOOB!

"

;

}

,

3000

)

;

Try it »

**Note:** Since setTimeout waits 3 seconds in the child thread, the main thread does not stop after the setTimeout function executes, so:

Example

setTimeout

(

function

(

)

{

document

.

getElementById

(

"

demo1

"

)

.

innerHTML

=

"

RUNOOB-1!

"

;

//

The child thread executes after three seconds

}

,

3000

)

;

document

.

getElementById

(

"

demo2

"

)

.

innerHTML

=

"

RUNOOB-2!

"

;

//

The main thread executes first

Try it »

The execution result of this program is:



RUNOOB-1!    // 三秒后子线程执行

RUNOOB-2!    // 主线程先执行


Asynchronous AJAX

Besides the setTimeout function, asynchronous callbacks are widely used in AJAX programming. For details about AJAX, see:https://www.runoob.com/ajax/ajax-tutorial.html

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

Example

var

xhr

=

new

XMLHttpRequest

(

)

;

xhr

.

onload

=

function

(

)

{

//

Outputs the received text data

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

xhr

.

responseText

;

}

xhr

.

onerror

=

function

(

)

{

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

"

Request error

"

;

}

//

Sends an asynchronous GET request

xhr

.

open

(

"

GET

"

,

"

https://www.runoob.com/try/ajax/ajax_info.txt

"

,

true

)

;

xhr

.

send

(

)

;

Try it »

The onload and onerror properties of XMLHttpRequest are both functions, called when the 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.runoob.com/try/ajax/demo_test.php

"

,

function

(

data

,

status

)

{

alert

(

"

Data:

"

data

"

\n

Status:

"

status

)

;

}

)

;

Try it »