Description of event loop (event loop), micro-tasks, macro task

First, understand the following points:

Why JS is single-threaded?

js as a major run in the browser's scripting language, is one of the main purposes js operation DOM. If there are two threads, multi-threaded operating JS on the same dom, issue a delete, edit a issue, this time the browser exactly how to enforce it?

JS Why asynchronous?

If the asynchronous JS does not exist, the only top-down execution, if the line is very long time to resolve, then the following code will be blocked. For users, it means blocking "stuck", thus leading to a poor user experience

JS is single-threaded asynchronous how to achieve it?

Since JS is single-threaded and can only be performed on a thread, and how to achieve asynchronous? Is the event loop (event loop) through the understanding of the event loop mechanism, to understand the mechanisms for implementation of JS

Multithreaded browser

  • GUI rendering thread (responsible for rendering HTML browser interface elements)
  • JavaScript engine thread (mainly responsible for dealing with Javascript script, such as V8 engine, GUI rendering and JavaScript engine thread thread mutually exclusive!)
  • Event trigger thread (such as a mouse click, AJAX asynchronous requests, etc.)
  • Thread clocked flip-flop (setTimeout, setInterval)
  • Asynchronous http request thread
  • Polling event processing thread (role: poll message queues, event loop)

When it comes to multi-threaded browser, we can talk about, how between the main thread and the thread is in line with the asynchronous: the main thread to initiate an asynchronous request (such as http requests), the corresponding worker thread receives the request and inform the main thread has been received notice (asynchronous function returns); the main thread can continue to execute the code behind, while the worker thread to perform asynchronous tasks; after the worker threads to complete the work, notify the main thread; the main thread after receiving the notification, perform certain actions (callback function);

javaScript event loop (event loop)

Because js is single-threaded so all tasks to be queued for execution, the task is divided into two types: macro tasks, micro-tasks

Macro task

Script (whole codes), setTimeout, setInterval, UI rendering, I / O, postMessage, MessageChannel, setImmediate (Node.js environment)

Micro-task

Promise, MutaionObserver, process.nextTick (Node.js environment)

Event Loop Process

  1. Execution of the macro task queue first task, after the implementation remove it
  2. Perform all of the micro-tasks to perform after removing them
  3. The next round macro task (repeating steps 2)

Macro Tasks> All micro Tasks> macro task so the cycle is formed event loop, where each round of execution A macro task And allMicro-task

Event Loop icon

Here Insert Picture Description

Examples

	console.log(1)
    setTimeout(function () {
        console.log(2);
    });
    new Promise(function(resolve,reject){
        console.log(3)
        resolve(4)
    }).then(function(val){
        console.log(val);
    })
    console.log(5);

The printed result is: 13542
Analysis:

  1. First, the main thread to perform the macro task execution from top to bottom, met console.log (1); print out 1
  2. Encounter setTimeout, it threw timer thread, and then continue down, and does not block the timer, the timer thread in here,After the main thread execution, The callback function intoMacro taskqueue.
  3. Experiencenew PromiseDirect enforcement, first print '3' out
  4. Encountered then promise, belonging to micro-task, put into the micro-task queue callback function
  5. Met console.log (5) Print '5' out
  6. After the implementation of the macro will perform all tasks micro-tasks to be performed, it would have printed '4' out.

So far the first round of the cycle has ended, the first round of the task in macro and micro tasks will be removed from the task queue, then open the second round of the cycle,

  1. First, find out whether you have a macro task, due to the setTimeout callback is placed in the macro task queue, where the code executes the callback function, printed '2' out
  2. Then find out whether there are micro-tasks, found no micro tasks, the end of the current round of cycle

Then repeat the steps above, this is the event loop. When we click on a subsequent trigger event, if there is a callback function, the callback function will be placed in the macro task queue, the queue once again have the task will be executed.

Extended question
of what results the following code to print out is?

console.log(1);

setTimeout(function(){
    new Promise(function(resolve){
    console.log('promise in setTimeout1');
    resolve();
    }).then(function(){
        console.log('then in setTimeout1');
    })
},10);

new Promise(function(resolve){
    console.log(3);
    for( var i=100000 ; i>0 ; i-- ){
        i==1 && resolve();
    }
    console.log(4)
}).then(function(){
    console.log(5);
});

setTimeout(function(){
    console.log('setTimeout2');
},10);

console.log(7);





The answer is as follows:
Here Insert Picture Description

This macro multiple tasks, the second setTimeout callback function, than the first setTimeout inside promise.then () callback to be executed later, because each cycle only execute a macro task, but it will execute all pending micro task execution, and the second macro setTimeout task queue at a position behind the first setTimeout.








This reference to a lot of big cattle resolve Thanks for watching please share ~

Published an original article · won praise 0 · Views 172

Guess you like

Origin blog.csdn.net/qq_39539687/article/details/100557701