How to understand sync and async in javascript

  The javascript language is a "single-threaded" language. Unlike the java language, a class inherits Thread and then a thread.start can open up a thread. Therefore, javascript is like an assembly line , just an assembly line, either processing or packaging. , multiple tasks and processes cannot be performed at the same time.

  So what exactly are synchronous and asynchronous here? If you really don't understand, I hope you read this article carefully. In fact, I personally feel that the official documentation of js is inaccurate when using two words, including many other words, which just sound advanced, but the actual application seems to have nothing to do with these words. For example, the word "event delegation", who do not know at first glance who can say what "event delegation" means? What event is delegated to? What kind of delegation, I think it is better to simply call it "the capture of events in the outer element", although it is a little longer, you can understand it at a glance.

  Getting back on track, "synchronized" - the word "together" comes to mind at once; "asynchronous", literally speaking, seems to be doing something on different (different) ways, the first word that comes to mind may be "While... while...", such as 'Xiao Ming eats ice cream while doing homework', this is completely fine, after eating ice cream, homework is also finished, is this asynchronous? That would be a big mistake!

  In fact, synchronous and asynchronous, in any case, there is only one pipeline (single thread) when doing things. The difference between synchronous and asynchronous is that the execution order of each process on this pipeline is different .

  The most basic asynchrony is the setTimeout and setInterval functions, which are very common, but few people know that this is actually asynchrony, because they can control the execution order of js. We can also simply understand that operations that can change the normal execution order of the program can be regarded as asynchronous operations. 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 is as follows: 1 5 2 3 4

 

  It can be seen that although we set the waiting time in setTimeout(function, time) to 0, the function in it is still executed later.

  火狐浏览器的api文档有这样一句话:Because even though setTimeout was called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity, not immediately. Currently executing code must complete before functions on the queue are executed, the resulting execution order may not be as expected.

  This means: although the time delay of setTimeout is 0, the function in it will also be put into a queue, waiting for the next opportunity to execute, the current code (referring to the program that does not need to be added to the queue) must be completed in the program of the queue done before, so the results may not be the same as expected.

  Here we talk about a "queue" (that is, the task queue ), what is placed in the queue, and the functions in setTimeout are placed, and these functions are added to the queue in turn, that is, the programs in all functions in the queue will be placed in the queue. All other codes are executed after execution, why is this? Because when the program is executed, the browser defaults to methods such as setTimeout and ajax request , which are time-consuming programs (although they may not be time-consuming) , and add them to a queue, which is a queue for storing time-consuming programs , after all the time-consuming programs are executed, the programs in the queue are executed in turn .

  Back to the original starting point - javascript is single threaded. Single-threaded means that all tasks need to be queued, and the next task will be executed after the previous task ends. If the former task takes a long time, the latter task has to wait forever. So there is a concept - task queue. If the queuing is due to the large amount of calculation and the CPU is too busy, it’s okay, but many times the CPU is idle, because the IO devices (input and output devices) are very slow (such as Ajax operations to read data from the network), you have to Wait for the result to come out, and then proceed to the next execution. So the designers of the JavaScript language realized that at this time, the main thread can completely ignore the IO device, suspend the waiting tasks, and run the tasks in the back first. Wait until the IO device returns the result, then go back and continue to execute the suspended task.

  Therefore, all tasks can be divided into two types, one is a synchronous task (synchronous), and the other is an asynchronous task (asynchronous). Synchronous tasks refer to tasks that are queued for execution on the main thread, and the next task can only be executed after the previous task is executed; asynchronous tasks refer to tasks that do not enter the main thread but enter the "task queue" (task queue) Task, only when the main thread task is executed, the "task queue" starts to notify the main thread and request to execute the task, the task will enter the main thread for execution.

  Specifically, the asynchronous operation mechanism is as follows:

  (1) All synchronization tasks are executed on the main thread, forming an execution context stack.
  (2) In addition to the main thread, there is also a "task queue" (task queue). As soon 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" are executed, the system will read the "task queue" to see what events are in it. Those corresponding asynchronous tasks then end the waiting state, enter the execution stack, and start execution.
  (4) The main thread keeps repeating the third step above.

  As long as the main thread is empty, it will read the "task queue", which is how JavaScript works. This process will keep repeating.  

  "Task queue" is a queue of events (which can also be understood as a queue of messages). When an IO device completes a task, an event is added to the "task queue", indicating that the related asynchronous task can enter the "execution stack". The main thread reads the "task queue", which is to read what events are in it.
The events in the "task queue", in addition to the events of the IO device, also include some user-generated events (such as mouse clicks, page scrolling, etc.), such as $(selectot).click(function), which are relatively time-consuming operation. As long as the callback functions of these events are specified, these events will enter the "task queue" when they occur, waiting for the main thread to read.
The so-called "callback function" (callback) is the code that will be suspended by the main thread. The function in the click event $(selectot).click(function) mentioned above is a callback function. An asynchronous task must specify a callback function. When the main thread starts to execute an asynchronous task, the corresponding callback function is executed. For example, ajax's success, complete, and error also specify their own callback functions, and these functions will be added to the "task queue" and wait for execution.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324854979&siteId=291194637