From promise to the event Loop, tasks, and Microtasks__java in JavaScript

Source: Internet
Author: User

A few days ago in the interview, encountered such a question:

Name the execution result of the following code:

settimeout (function () {
    console.log (1)
}, 0);

New Promise (function executor (resolve) {
        resolve ();
}). Then (function () {
    console.log (2);
});   2,1
(function test () {
 settimeout (function () {Console.log (4)}, 0);
 New Promise (function executor (resolve) {
 console.log (1);
 for (var i=0 i<10000; i++) {
 i = = 9999 && resolve ();
 }
 Console.log (2);
 }). Then (function () {
 console.log (5);
 });
 Console.log (3);
}) ()  //1,2,3,5,4

In order to find out the reason for the results of the operation, we want to start from the JS event loop, referring to some of the online documents, according to my own understanding, sorted as follows:

One, why JavaScript is a single thread

One of the main features of JavaScript language is single-threaded, that is, one thing at a time. So why can't javascript have multiple threads? This will improve efficiency.

A single thread of JavaScript, which is related to its purpose. As a browser scripting language, the main purpose of JavaScript is to interact with the user and manipulate the DOM. This determines that it can only be single-threaded, or it can create complex synchronization problems. For example, assuming that JavaScript has two threads at the same time, one thread adds content to one of the DOM nodes, and another thread deletes the node, which thread the browser should use.

Therefore, in order to avoid complexity, from the birth, JavaScript is a single thread, which has become the core characteristics of the language, will not change in the future.

To take advantage of the computational power of multi-core CPUs, HTML5 proposes web worker standards that allow JavaScript scripts to create multiple threads, but the child threads are completely controlled by the main thread and must not manipulate the DOM. So, the new standard doesn't change the nature of JavaScript single-threaded threads.

second, the task queue

A single thread means that all tasks need to be queued and the previous task is completed before the latter task is performed. If the previous task takes a long time, the latter task will have to wait all the time.

If the queue is because of the large amount of calculation, CPU busy, but also forget, but many times the CPU is idle, because the IO device (input) is very slow (such as AJAX operations from the network to read data), had to wait for the results out, and then down.

The designer of the JavaScript language realizes that the main thread can completely ignore the IO device, suspend the task in wait, and run the task in the back first. Wait until the IO device returns the result, and then go back to the pending task.

As a result, all tasks can be divided into two types, one is the synchronization task (synchronous) and the other is the asynchronous task (asynchronous). A synchronization task is a task that is queued for execution on the main thread. The last task can be performed only after the previous task has finished executing; the asynchronous task refers to a task that does not enter the main thread and goes into the task queue, only the task queue notifies the main thread, and an asynchronous task can execute. The task will not enter the main thread execution.

Specifically, the operating mechanism for asynchronous execution is as follows. (This is also true for synchronous execution, because it can be considered asynchronous execution without an asynchronous task.) )

(1) All synchronization tasks are performed on the main thread, forming an execution stack (execution context stack).
(2) There is also a "task queue" in the main thread. 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 completed, the system reads "task queues" to see what events are inside. Those corresponding asynchronous tasks, then end the wait state, into the execution stack, start execution.
(4) The main thread continues to repeat the third step above.

Third, Timer

In addition to the events that place asynchronous tasks, task queues can place timed events that specify how long some code will be executed. This is called the timer function, which is the code that executes regularly.
The function of the timer is mainly performed by settimeout () and SetInterval (), and their internal operating mechanism is exactly the same, except that the code specified by the former is executed once and the latter is executed repeatedly. The following main discussion settimeout ().

SetTimeout () accepts two parameters, the first is a callback function, and the second is the number of milliseconds to defer execution.

Console.log (1);
settimeout (function () {Console.log (2);},1000);
Console.log (3);

The result of the above code is 1,3,2, because settimeout () delays the second row to 1000 milliseconds after execution.

If the second argument to SetTimeout () is set to 0, the callback function specified (0 millisecond interval) is executed immediately after the current code finishes (execution stack emptying).

settimeout (function () {console.log (1);}, 0);
Console.log (2);

The results of the above code are always 2,1, because only after the second row is executed does the system perform the callback function in the task queue.

In short, the meaning of settimeout (fn,0) is to specify that a task executes at the earliest available idle time of the main thread, that is, as early as possible. It adds an event at the end of the task queue, so it will not be executed until both the synchronization task and the task queue existing events have been processed.

The HTML5 standard sets the minimum (shortest interval) of the second parameter of settimeout () to be less than 4 milliseconds, and automatically increases if it is below this value. Prior to this, older browsers set the minimum interval to 10 milliseconds. In addition, changes to those DOM, especially those that involve page rendering, are usually not performed immediately, but are performed every 16 milliseconds. The effect of using requestanimationframe () is better than settimeout ().

It is important to note that settimeout () simply inserts the event into the task queue, and the main thread does not execute the callback function it specifies until the current code (the execution stack) has been executed. If the current code takes a long time, it may have to wait long, so there is no way to guarantee that the callback function must be executed at the settimeout () specified.

Four, the Event Loop

In fact, there are at least three things in JS running: Task queue Microtask Queue stack

And then above, promise is how to do it asynchronously.

Promise is not a task, it belongs to Microtask, what is Microtask?

Microtasks are usually scheduled for things that should happen
Straight after the currently executing script, such as reacting to a
Batch of actions, or to make something async without taking the
Penalty of a whole new task.

The feeling can call it a micro-task to follow at the end of a task, like a small valet.

It means that promise belongs to the Microtask queue, and settimeout belongs to the task queue. These two asynchronous queues are different, and the asynchronous queue that promise is in has a higher priority.

Reference documents:
Http://www.ruanyifeng.com/blog/2014/10/event-loop.html
Http://www.jianshu.com/p/1ee6c21f6efa

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.