JavaScript asynchronous mechanism

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u012193330/article/details/60752142

Look at the two code snippets js

for  (var i = 1; i <= 5; i++) {
      setTimeout(function(){
          console.log(i);
      }, 0);
}

Result: The output 5 6

var start = new Date;
setTimeout(function(){
    var end = new Date;
    console.log('Time elapsed:', end - start, 'ms');
}, 500);
while (new Date - start < 1000) {};

Results: Time elapsed 1020ms (different machines have different values, but will be slightly greater than 1000)

The reason why the above results, as a result of setTimeout is executed asynchronously, js specific asynchronous mechanism as shown below:

Write pictures described here

Asynchronous execution is the most important characteristic of javascript, it works: js execution engine is only one main thread code execution logic, encounters a task code needs to be executed asynchronously, it is added event queue. When the main thread is idle, polling the event queue task can be performed, attach it to the main thread of execution, and so on, until the event queue non-executable tasks.

JS engine just execution in the event queue asynchronous code, but the sources of information in the event queue is not the JS engine, but by the browser in other threads, as shown below:

Write pictures described here

Http transmission to the thread as an example:
The most common is the js code issues ajax request, then that is handed over to the browser http thread to handle, and when the back-end data return, http thread to generate a good data is ready in the event queue the event, JS execution while waiting for the main thread is idle.
Another example is our common click, mouse events, event-triggered GUI thread are generated. When users click on the page, GUI thread will generate event triggers a click event in the event queue, waiting to be executed when the main thread JS idle.

Guess you like

Origin blog.csdn.net/u012193330/article/details/60752142