How to understand synchronous and asynchronous in JavaScript

Source: Internet
Author: User

JavaScript language is a "single-threaded" language, unlike the Java language, class inherits thread and then a thread.start can open a thread, so JavaScript is like a pipeline , just a pipeline, It is either processed or packaged, and multiple tasks and processes cannot be performed at the same time.

So what's the point of synchronization and Asynchrony? If you really don't understand, I hope you read this article carefully. In fact, I personally think that JS official documents in the use of two words is not accurate, including a lot of other words, all just sound advanced, but the actual application seems to be with these words not half a dime relationship. For example, the word "event delegate", who knows at first glance who can say "event delegation"? What events are entrusted? How to delegate, I think it is better to simply call "event in the outer element of the capture", although a little longer, you can read.

Back on track, "Sync"--a word that reminds people of "together", "async", literally, like doing something on different ways, the first word that might be "one side ..." One side ... ", such as" Xiao Ming while eating ice cream while writing industry, "This is completely no problem, ice cream has finished, homework is finished, this is asynchronous? That's a big mistake!

In fact, synchronous and asynchronous, in any case, the time to do things are only one pipeline (single-threaded), synchronous and asynchronous difference is that the pipeline on the execution of the various processes in different order .

The most basic asynchronous is settimeout and setinterval functions, very common, but few people know that this is asynchronous, because they can control the sequence of JS execution. We can also simply understand that an operation that alters the order of the program's normal execution can be seen as an asynchronous operation. The following code:

        

<script type="Text/javascript" >

Console.log ( "1");

SetTimeout (function () {

Console.log ( "2")

}, 0);

SetTimeout (function () {

Console.log ( "3")

}, 0);

SetTimeout (function () {

Console.log ( "4")

}, 0);

Console.log ( "5");

</script>

The output results are as follows:1 5 2 3 4

As you can see, although we set the wait time in settimeout (Function,time) to 0, the function in the result is executed later.

Firefox API documentation has this sentence: Because even though was setTimeout called with a delay of zero, it's placed on a queue and scheduled to run a T the next opportunity, not immediately. Currently executing code must complete before functions on the queue is executed, the resulting execution order may not B e As expected.

This means that although the time delay of settimeout is 0, the function in it will be placed in a queue, waiting for the next opportunity to execute, and the current code (that is, a program that does not need to join the queue) must be completed before the program of that queue finishes, so the result may not be the same as the expected result.

Here is a "queue" (that is, the task queue ), what is the queue, put is the function in the settimeout, these functions in turn to join the queue, That is, the program in all the function in the queue will execute after all the code outside the queue is executed. Because in the execution of the program, the browser will default setTimeout and Ajax requests This kind of method is time-consuming program (although it may not be time-consuming), add it to a queue, The queue is a queue that stores time-consuming programs, and then executes the programs in that queue in turn after all time-consuming programs are executed .

Back to the original starting point--javascript is a single thread. A single thread means that all tasks need to be queued, and the previous task is completed before the latter one is executed. If the previous task takes a long time, the latter task has to wait. So there is a concept-the task queue. If the queue is because of large computational capacity, the CPU is not busy, but also forget, but many times the CPU is idle, because the IO device (input) is very slow (such as the Ajax operation from the network to read data), have to wait for the results, and then down to execute. The JavaScript designer realizes that at this point the main thread can completely ignore the IO device, suspend the task in wait, and run the task in the queue first. Wait until the IO device returns the result, and then go back and put the suspended task on hold.

Thus, all tasks can be divided into two types, one synchronization task (synchronous) and one asynchronous task (asynchronous). A synchronization task is a task that is queued on the main thread to perform the latter task only if the previous task is completed, and the asynchronous task refers to a task that goes into the task queue without entering the main thread, and the task queue begins to notify the main thread when the main thread task finishes executing. The task does not go into the main thread execution until the task is requested.

Specifically, the asynchronous run mechanism is as follows:

(1) All synchronization tasks are performed on the main thread, forming an execution stack (execution context stack).
(2) In addition to the main thread, there is a task queue. As long as the asynchronous task has a running result, an event is placed in the task queue.
(3) Once all the synchronization tasks in the "execution stack" have been executed, the system reads the "task queue" to see what events are in it. Those corresponding asynchronous tasks, so end the wait state, go to the execution stack, and start execution.
(4) The main thread constantly repeats the third step above.

As long as the main line Cheng, will read "task queue", this is the operation mechanism of JavaScript. This process is repeated.

The task queue is a queue of events (which can also be understood as a queue of messages), and the IO device completes a task by adding an event in the task queue that indicates that the associated asynchronous task can enter the execution stack. The main thread reads the "Task queue", which is what events are read inside.
Events in the task queue, in addition to the IO device events, include some user-generated events (such as mouse clicks, page scrolling, and so on), such as $ (Selectot). Click (function), which are relatively time-consuming operations. As long as the callback functions for these events are specified, these events go into the task queue and wait for the main thread to read.
The so-called "callback function" (callback), is the code that will be hung up by the main thread, the previous click event $ (selectot). The function in click is a callback function. An asynchronous task must specify a callback function that executes the corresponding callback function when the main thread starts executing an asynchronous task. For example, Ajax Success,complete,error also specify their own callback functions, which are added to the "task queue" for execution.

How to understand synchronous and asynchronous in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.