Home > Web Front-end > JS Tutorial > body text

Detailed explanation of JavaScript event loop mechanism

青灯夜游
Release: 2018-10-08 15:30:43
forward
2275 people have browsed it

This article shares with you relevant knowledge points about the JavaScript event loop mechanism. Friends who are interested can learn and refer to it.

As we all know, JavaScript is a single-threaded language. Although Web-Worker was proposed in html5, this has not changed the core of JavaScript being single-threaded. See this passage in the HTML specification:

To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section. There are two kinds of event loops: those for browsing contexts, and those for workers.

To coordinate events, user interaction, scripting, UI rendering, and network processing, user engines must use event loops. Event Loop consists of two types: one based on Browsing Context and one based on Worker, both of which run independently. The following article uses an example to focus on the event loop mechanism based on Browsing Context.

Let’s take a look at the following JavaScript code:

console.log('script start');

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

Promise.resolve().then(function() {
 console.log('promise1');
}).then(function() {
 console.log('promise2');
});

console.log('script end');
Copy after login
Copy after login

First guess the output sequence of this code, then enter it in the browser console to see if the actual output sequence matches yours. Is the guessed order consistent? If so, it means that you still have a certain understanding of the JavaScript event loop mechanism. Keep reading to consolidate your knowledge; and if the actual output order is inconsistent with your guess, Then the following part of this article will answer your questions.

Task Queue

All tasks can be divided into synchronous tasks and asynchronous tasks. Synchronous tasks, as the name suggests, are tasks that are executed immediately. Synchronous tasks generally enter the main thread directly for execution; and Asynchronous tasks are tasks that are executed asynchronously, such as ajax network requests, setTimeout timing functions, etc., which are all asynchronous tasks. Asynchronous tasks are coordinated through the task queue (Event Queue) mechanism. The following figure can be used to roughly explain the specific situation:

# Synchronous and asynchronous tasks enter different execution environments respectively. The synchronous tasks enter the main thread, that is, the main execution stack, and the asynchronous tasks enter the main thread, that is, the main execution stack. Enter the Event Queue. If the tasks in the main thread are empty after execution, the corresponding tasks will be read from the Event Queue and pushed to the main thread for execution. The continuous repetition of the above process is what we call Event Loop.

In the event loop, each loop operation is called a tick. By reading the specification, we can know that the task processing model of each tick is relatively complex, and its key steps can be summarized as follows:

  • Select the oldest task that enters the queue first in this tick. If there is one, execute it (once)

  • Check whether Microtasks exist, if they exist Then continue to execute until the Microtask Queue is cleared

  • Update render

The main thread repeats the above steps

You can use a picture to illustrate the process:

I believe someone will want to ask, what are microtasks? The specification stipulates that tasks are divided into two categories, namely Macro Task (macro task) and Micro Task (micro task), and after each macro task is completed, all micro tasks must be cleared. The Macro Task here is also what we often call task. Some articles do not distinguish between them. The tasks mentioned in the following articles are all regarded as macro tasks.

(macro)task mainly includes: script (overall code), setTimeout, setInterval, I/O, UI interactive events, setImmediate (Node.js environment)

microtask mainly includes: Promise, MutaionObserver, process.nextTick (Node.js environment)

setTimeout/Promise and other APIs are task sources, and what enters the task queue is the specific execution task specified by them. Tasks from different task sources will enter different task queues. Among them, setTimeout and setInterval have the same origin.

Analysis of sample code

There are thousands of words, so it is better to explain it clearly with examples. Below we can follow the specifications and analyze the above example step by step. First, post the example code (to save you from scrolling up).

console.log('script start');

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

Promise.resolve().then(function() {
 console.log('promise1');
}).then(function() {
 console.log('promise2');
});

console.log('script end');
Copy after login
Copy after login

The overall script enters the main thread as the first macro task, encounters console.log, and outputs script start

  • Encounters setTimeout, and its callback function is distributed to When

  • encounters a Promise in the macro task Event Queue, its then function is assigned to the micro task Event Queue and is recorded as then1. Then it encounters the then function again and assigns it to the micro task Event Queue. In the task Event Queue, it is recorded as then2

  • When it encounters console.log, it outputs script end

##At this point, it exists in the Event Queue Three tasks, as shown in the following table:

Macro taskMicro task setTimeoutthen1-then2
  • 执行微任务,首先执行then1,输出 promise1, 然后执行 then2,输出 promise2,这样就清空了所有微任务

  • 执行 setTimeout 任务,输出 setTimeout 至此,输出的顺序是:script start, script end, promise1, promise2, setTimeout

so,你猜对了吗?

看看你掌握了没

再来一个题目,来做个练习:

console.log('script start');

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

new Promise(resolve => {
 console.log('promise1');
 resolve();
 setTimeout(() => console.log('timeout2'), 10);
}).then(function() {
 console.log('then1')
})

console.log('script end');
Copy after login

这个题目就稍微有点复杂了,我们再分析下:

首先,事件循环从宏任务 (macrotask) 队列开始,最初始,宏任务队列中,只有一个 scrip t(整体代码)任务;当遇到任务源 (task source) 时,则会先分发任务到对应的任务队列中去。所以,就和上面例子类似,首先遇到了console.log,输出 script start; 接着往下走,遇到 setTimeout 任务源,将其分发到任务队列中去,记为 timeout1; 接着遇到 promise,new promise 中的代码立即执行,输出 promise1, 然后执行 resolve ,遇到 setTimeout ,将其分发到任务队列中去,记为 timemout2, 将其 then 分发到微任务队列中去,记为 then1; 接着遇到 console.log 代码,直接输出 script end 接着检查微任务队列,发现有个 then1 微任务,执行,输出then1 再检查微任务队列,发现已经清空,则开始检查宏任务队列,执行 timeout1,输出 timeout1; 接着执行 timeout2,输出 timeout2 至此,所有的都队列都已清空,执行完毕。其输出的顺序依次是:script start, promise1, script end, then1, timeout1, timeout2

用流程图看更清晰:

总结

有个小 tip:从规范来看,microtask 优先于 task 执行,所以如果有需要优先执行的逻辑,放入microtask 队列会比 task 更早的被执行。

最后的最后,记住,JavaScript 是一门单线程语言,异步操作都是放到事件循环队列里面,等待主执行栈来执行的,并没有专门的异步执行线程。

以上就是本章的全部内容,更多相关教程请访问JavaScript视频教程

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

Related labels:
source:jb51.net
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!