Home > Web Front-end > JS Tutorial > Detailed explanation of JavaScript event loop mechanism - Lecture 1

Detailed explanation of JavaScript event loop mechanism - Lecture 1

韦小宝
Release: 2018-03-07 14:56:13
Original
1724 people have browsed it

Event loop mechanism in Javascript, many articles only say that Javascript events are divided into synchronous tasks and asynchronous tasks. When a synchronous task is encountered, it is placed in the execution stack for execution, and when an asynchronous task is encountered, Put it in the task queue and wait until the execution stack is completed before executing the events in the task queue. This article is very good! We together look! Let’s get straight to the point!

Function call stack and task queue

Javascript has a main thread main process and a call-stack (a call stack). While the task in the call stack is being processed, everything else has to wait. When some asynchronous operations such as setTimeout are encountered during execution, they will be handed over to other modules of the browser (taking webkit as an example, the webcore module) for processing. When the delayed execution time specified by setTimeout is reached, task(Callback function) will be put into the task queue. Generally, the callback functions of different asynchronous tasks will be placed in different task queues. After all tasks in the call stack have been executed, then execute the tasks (callback functions) in the task queue.

Using a picture from Philip Roberts's speech "Help, I'm stuck in an event-loop" is

Detailed explanation of JavaScript event loop mechanism - Lecture 1

in the picture above , when the call stack encounters DOM operations, ajax requests, setTimeout and other WebAPIs, it will be handed over to other modules of the browser kernel for processing. In addition to the Javasctipt execution engine, the webkit kernel has an important The module is the webcore module. For the three APIs mentioned by WebAPIs in the figure, webcore provides DOM Binding, network, and timer modules respectively to handle the underlying implementation. When these modules finish processing these operations, put the callback function into the task queue, and then wait for the tasks in the stack to be executed before executing the callback function in the task queue.

Looking at the event loop mechanism from setTimeout

The following uses an example from Philip Roberts's speech to illustrate how the event loop mechanism executes setTimeout. of.

Detailed explanation of JavaScript event loop mechanism - Lecture 1

First the execution context of the main() function is pushed onto the stack

Detailed explanation of JavaScript event loop mechanism - Lecture 1

The code is then executed and encounters console.log( 'Hi'), at this time log('Hi') is pushed onto the stack. The console.log method is just a common method supported by the webkit kernel, so the log('Hi') method is executed immediately. At this time, 'Hi' is output.

Detailed explanation of JavaScript event loop mechanism - Lecture 1

#When encountering setTimeout, the execution engine adds it to the stack.

Detailed explanation of JavaScript event loop mechanism - Lecture 1

The call stack found that setTimeout is an API in the WebAPIs mentioned before, so after popping it off the stack, the delayed execution function is handed over to the browser's timer module for processing. .

Detailed explanation of JavaScript event loop mechanism - Lecture 1

The timer module handles delayed execution functions. At this time, the execution engine then executes and adds log(‘SJS’) to the stack, and outputs ‘SJS’.

Detailed explanation of JavaScript event loop mechanism - Lecture 1

When the time specified by the delay method in the timer module is up, it is put into the task queue. At this time, all tasks in the call stack have been executed.

Detailed explanation of JavaScript event loop mechanism - Lecture 1

Detailed explanation of JavaScript event loop mechanism - Lecture 1

After the task in the call stack is executed, the execution engine will then check whether there is anything in the execution task queue that needs to be executed. Callback. The cb function here is added to the call stack by the execution engine, and then executes the code inside and outputs 'there'. Wait until the execution is completed before popping it off the stack.

Summary

The above process explains how the browser executes it when it encounters setTimeout. Similar ones are The other APIs mentioned in the previous figure and some other asynchronous operations.
To summarize what was said above, the main points are the following:

1. All codes must be executed through calls in the function call stack.

2. When encountering the APIs mentioned in the previous article, it will be handed over to other modules of the browser kernel for processing.

3. The callback function is stored in the task queue.

4. Wait until the task in the call stack is executed and then go back to execute the task in the task queue.

Test

for (var i = 0; i < 5; i++) {
    setTimeout(function() {
      console.log(new Date, i);
    }, 1000);
}
console.log(new Date, i);
Copy after login

This code is a JS interview question that 80% of applicants fail from an article I read online not long ago Found in , now we will analyze how this code outputs the final execution state mentioned in the last article:

40% of people will describe it as: 5 -> 5,5,5,5,5, that is, the first 5 is output directly, and after 1 second, 5 5s are output;

1. First, when i=0, the condition is met , the execution stack executes the code in the loop body, and finds that it is setTimeout. After popping it out of the stack, the delayed execution function is handed over to the Timer module for processing.

2. When i=1,2,3,4, the conditions are all met, and the situation is the same as when i=0. Therefore, there are 5 identical delayed execution functions in the timer module.

3. When i=5, the condition is not met, so for loop ends, console.log(new Date, i) is pushed onto the stack, and i at this time has become 5. So the output is 5.

4. At this time, 1s has passed, and the timer module returns the 5 callback functions to the task queue in the order of registration.

5. The execution engine executes the functions in the task queue. Five functions are pushed into the stack for execution and then popped out. At this time, i has become 5. So five 5s are output almost simultaneously.

6. Therefore, the waiting time of 1s is actually only 1s after outputting the first 5. This 1s time is the specified 1s time that the timer module needs to wait before handing the callback function to the task queue. After the execution stack is completed, execute the five callback functions in the task queue. There is no need to wait 1s during this period. Therefore, the output status is: 5 -> 5,5,5,5,5, that is, the first 5 is output directly, and after 1s, 5 5s are output;

Question

After seeing this, I have a general understanding of the event loop mechanism, but if I think about it carefully, there are some other issues worth exploring.
The following is explained through a chestnut:

(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);
})()
Copy after login

In this code, there is an extra promise, then we can think about the following question:

1. The task of the promise will be placed In different task queues, what is the execution order of setTimeout's task queue and promise's task queue?

2. Now that you have seen that I have talked about so many tasks, what exactly do the tasks mentioned above include? How is it divided specifically?

If you still don’t understand it well here, then I will go on to explain in detail the event loop mechanism of different tasks.

Related recommendations:

##js event loop mechanism example analysis

The above is the detailed content of Detailed explanation of JavaScript event loop mechanism - Lecture 1. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template