当前位置:网站首页>Detailed explanation of event cycle
Detailed explanation of event cycle
2022-07-04 04:23:00 【Careteen】
Catalog
- Event cycle mechanism
- Browser's event loop
- What are the macro tasks and micro tasks in the browser
- setImmediate/setTimeout
- MessageChannel
- promise Of then Method
- MutationObserver
- Detailed explanation of interview questions
- What are the macro tasks and micro tasks in the browser
- Node The event loop of
Event cycle mechanism
First understand the task queue
- All synchronization tasks are performed on the main thread , Form an execution stack
- Outside the main thread , There is also a task queue . As long as asynchronous tasks have run results , Just put an event in the task queue .
- Once all synchronization tasks in the execution stack are completed , The system will read the task queue , See what's going on inside . Those corresponding asynchronous tasks , So the waiting state is ended , Enter the execution stack , Start execution .
- The main thread repeats step 3 above .
At this time, it is divided into Browser's event loop and Node End event loop . The following will explain in detail .
Browser's event loop
The main thread reads events from the task queue , The process is cyclical , So the whole operation mechanism is also called Event Loop( The event loop )
The above process is a macro representation , actually callback queue
Task queues are divided into macro task
Macro tasks and micro task
There are two kinds of micro tasks .
In a cycle of events , The steps are as follows :
- First, put the synchronization code into the execution stack for execution , If there is an asynchronous event, its return result will be put into a task queue . Task queue is divided into macro task queue and micro task queue .
- When the execution stack is empty , Priority will be given to checking whether there are events in the micro task queue
- If exist , Then execute the corresponding callback in the queue event in turn , Until the micro task queue is empty , Go to the next step
- If it does not exist , Jump to the next step
- Check whether there are events in the macro task queue
- If exist , Then put the corresponding callback of the event in the queue into the execution stack for execution
- If it does not exist , Jump to the next step
- If there is asynchronous code in the execution stack , Then put it into the next task queue . Repeat the first three steps
From the above, we know that the focus is to give priority to micro tasks and then macro tasks after the execution stack is empty .
What are the macro tasks and micro tasks in the browser
Yes vue Students should be familiar with a method this.$nextTick(() => { ... })
, At this time, we are at a loss about the classification of macro tasks and micro tasks , Then look at it. vue How to deal with it in the source code .
The definition is very clear
- Macro task
- setImmediate
- MessageChannel
- setTimeout
- Micro task
- promise Of then Method
- MutationObserver (vue2.0 This has been abandoned API)
setImmediate/setTimeout
setImmediate by IE Peculiar , We can do it in IE Test in browser environment
setImmediate(() => { console.log('setImmediate') }) setTimeout(() => { console.log('setTimeout') }, 0) // The delay is set to 0, In fact, there will be 4ms Delay of . // => setImmediate // setTimeout
MessageChannel
H5 Of API, Compatibility is not very good , Go to mdn View usage
Then do the following tests
let channel = new MessageChannel() let port1 = channel.port1 let port2 = channel.port2 port1.postMessage('hello careteen ~') port2.onmessage = function (e) { console.log(e.data) } // => hello careteen ~
promise Of then Method
Promise.resolve(100).then(data => { console.log(data) }) // => 100
MutationObserver This is also an asynchronous method belonging to micro tasks , Go to mdn View usage
In this method vue1.0 Used in , But again 2.0 Later, it was abandoned .
Here's a brief introduction to using , The scenario is to create multiple nodes for the page , Tell us when the node is created .
html
<div id="box"></div>
js
let observer = new MutationObserver(function() { console.log('dom Update completed ') console.log(box.children.length) }) // Monitor the changes of future generations observer.observe(box, { childList: true }) for (let i = 0; i < 5; i++) { box.appendChild(document.createElement('sapn')) } for (let i = 0; i < 10; i++) { box.appendChild(document.createElement('p')) } // => When the node is created // dom Update completed // 15
Detailed explanation of interview questions
case1:
Promise.resolve().then(() => { console.log('then1') setTimeout(() => { console.log('timer1') }, 0) }) console.log('start') setTimeout(() => { console.log('timer2') Promise.resolve().then(() => { console.log('then2') }) }, 0) // => start -> then1 -> timer2 -> then2 -> timer1
According to the above execution process, we can know the result .
- Execute synchronization code first
start
, - promise Of then Method into the micro task queue ,
- Then execute the synchronization code
then1
- take setTimeout Put in the macro task queue
- Then execute the synchronization code
- setTimeout Put the callback of into the macro task queue
- wait until setTimeout2 time out
- perform setTimeout2 Synchronization code of callback
timer2
- promise Of then Method into the micro task queue , And then execute
then2
- wait until setTimeout1 It's time to , Execute the synchronization code inside
- perform setTimeout2 Synchronization code of callback
Node The event loop of
- V8 Engine parsing JavaScript Script .
- The parsed code , call Node API.
- libuv The library is responsible for Node API Implementation . It assigns different tasks to different threads , To form a Event Loop( The event loop ), Returns the execution result of the task asynchronously V8 engine .
- V8 The engine then returns the result to the user .
The above is just a macro description , Like the browser , The queue of asynchronous event methods is also subdivided into several . Go to Node Official website See the detailed description
Here's an excerpt from Node Official website
┌───────────────────────────┐ ┌─>│ timers │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ pending callbacks │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ idle, prepare │ │ └─────────────┬─────────────┘ ┌───────────────┐ │ ┌─────────────┴─────────────┐ │ incoming: │ │ │ poll │<─────┤ connections, │ │ └─────────────┬─────────────┘ │ data, etc. │ │ ┌─────────────┴─────────────┐ └───────────────┘ │ │ check │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ └──┤ close callbacks │ └───────────────────────────┘
From the above model, we can know the execution order of the mechanism :
External input data --> Polling phase (poll)--> The check phase (check)--> Close the event callback phase (close callback)--> Timer detection phase (timer)-->I/O Event callback phase (I/O callbacks)--> Idle phase (idle, prepare)--> Polling phase ...
Several asynchronous queues subdivided :
- timers Stage
setTimeout
MethodsetInterval
Method
- pending callbacks Stage
- I/O Read and write operations . Such as
fs.readFile()
Method
- I/O Read and write operations . Such as
- idle, prepare Stage
- For internal use only , We don't need to pay attention to
- poll Stage
- Retrieve new I/O event , Execution and I/O Related callbacks ( In addition to turning off callbacks 、 Timer scheduling callbacks and setimmediation() outside , This is true for almost all callbacks ); Nodes will block here at the right time .
- check Stage
setImmediate()
The callback of will be executed at this stage
- close callbacks Stage
- for example
socket.on('close', ...)
such close Event callback
- for example
It is different from the browser's event cycle mechanism :
- First of all, it will be in
poll
Stage- To look at first
poll queue
Is there an event in- If you have any , Then execute the callback in the order of first in first out
- If there is no , Will check whether there is
setImmediate
The callback- If there is such a callback , Will enter below
check
Stage to execute these callbacks
- If there is such a callback , Will enter below
- At the same time , Check whether there are expired
timer
- If you have any , These expired
timer
The callback of is placed intimer queue
, Then cycle intotimer
The stage executes the callback in the queue
- If you have any , These expired
setImmediate
andtimer
The order of judgment is not fixed , Affected by the code running environment- If
setImmediate
andtimer
All queues are empty , Then the cycle will bepoll
Stage stop , Until there is one I/O Event return , The cycle will go intoI/O callback
Stage and immediately execute the callback of this event
- To look at first
check
Stage- This stage is dedicated to
setImmediate
The callback , Whenpoll
Phase goes into idle state , alsosetImmediate
In the queue callback when , The cycle of events enters this stage
- This stage is dedicated to
close
Stage- When one socket Connect or a handle When suddenly closed ( For example, call
socket.destroy()
Method ),close The event is sent to this stage to execute the callback . Otherwise the event will useprocess.nextTick()
Method send out
- When one socket Connect or a handle When suddenly closed ( For example, call
timer
Stage- This stage performs all due... In a first in, first out fashion timer Join in timer In the line callback, One timer callback It means a pass setTimeout perhaps setInterval Callback function set by function
I/O callback
Stage- As mentioned above , This stage mainly implements most of I/O Event callback , Include some callbacks for the operating system . For example, one TCP When a connection makes a mistake , The system needs to execute a callback to get this error report .
- So repeatedly
- Special :
process.nextTick()
Although this method is not listed above , But it is called first when each stage is completed and ready to enter the next stage- And execution
poll queue
The task of is different , This operation will not stop until the queue is cleared . In other words, incorrect use will lead to node Into a dead cycle , Until memory leaks
- And execution
Detailed explanation of interview questions
It says a big push , It looks boring , Then here are a few case In depth understanding of
case1:
Promise.resolve().then(() => { console.log('then1') setTimeout(() => { console.log('timer1') }, 0) }) setTimeout(() => { console.log('timer2') Promise.resolve().then(() => { console.log('then2') }) }, 0) // => then1 -> timer2 -> then2 -> timer1 // or then1 -> timer2 -> timer1 -> then2
The result of the above code has two possibilities ,then2
After execution ,timer1
It may not be time yet, or it may be time , because setTimeout
If the second parameter of the method is set to 0
, There will be 4ms
Delay of .
case2:
setTimeout(() => { console.log('timeout') }, 0) setImmediate(() => { console.log('setImmediate') }) // => setImmediate -> timeout // or timeout -> setImmediate
Run it a few more times , The running result is not certain , It depends on the environment in which the code runs . Various complexities in the operation and environment will lead to the random determination of the order of the two methods in the synchronization queue .
Let's take another example case3:
let fs = require('fs') fs.readFile('1.setImmediate.html', () => { setTimeout(() => { console.log('timeout') }, 0) setImmediate(() => { console.log('setImmediate') }) }) // => setImmediate -> timeout
Review the stages mentioned above , stay I/O event
In the callback ,setImmediate
The callback of always takes precedence over setTimeout
Callback execution of . So the order of return results is fixed .
link
Node series - Next section Touch your hand and give you a hand commonjs standard
边栏推荐
- Redis:哈希hash类型数据操作命令
- idea修改主体颜色
- Msgraphmailbag - search only driveitems of file types
- 资深开发人员告诉你,怎样编写出优秀的代码?
- Rhcsa-- day one
- Leetcode skimming: binary tree 07 (maximum depth of binary tree)
- [csrf-01] basic principle and attack and defense of Cross Site Request Forgery vulnerability
- VIM add interval annotation correctly
- tdk-lambda电源主要应用
- How to add custom API objects in kubernetes (1)
猜你喜欢
User defined path and file name of Baidu editor in laravel admin
Leetcode brush question: binary tree 06 (symmetric binary tree)
R语言中如何查看已安装的R包
The three-year revenue is 3.531 billion, and this Jiangxi old watch is going to IPO
Parameterization of controls in katalon
深度优先搜索简要讲解(附带基础题)
The maximum expiration time of client secret in azure ad application registration is modified to 2 years
Flink学习6:编程模型
There is a problem that the package cannot be parsed in the like project
还原窗口位置的微妙之处
随机推荐
Unity资源路径
RHCSA 06 - suid, sgid, sticky bit(待补充)
hbuildx中夜神模拟器的配置以及热更新
【华为云IoT】读书笔记之《万物互联:物联网核心技术与安全》第3章(上)
(指针)自己写一个比较字符串大小的函数,功能与strcmp类似。
(指针)编写函数void fun(int x,int *pp,int *n)
Leetcode brush question: binary tree 06 (symmetric binary tree)
统计遗传学:第三章,群体遗传
*. No main manifest attribute in jar
【读书会第十三期】视频文件的封装格式
Exercises in quantum mechanics
Pytest multi process / multi thread execution test case
Redis cluster uses Lua script. Lua script can also be used for different slots
Storage of MySQL database
VIM mapping command
【微服务|openfeign】@FeignClient详解
RHCSA 01 - 创建分区与文件系统
NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
Redis cluster view the slots of each node
Katalon使用script实现查询List大小