当前位置:网站首页>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
边栏推荐
- leetcode刷题:二叉树08(N叉树的最大深度)
- Balance between picture performance of unity mobile game performance optimization spectrum and GPU pressure
- Flink学习6:编程模型
- 02 ls 命令的具体实现
- RHCSA 06 - suid, sgid, sticky bit(待补充)
- 毕业三年,远程半年 | 社区征文
- 【愚公系列】2022年7月 Go教学课程 002-Go语言环境安装
- Katalon使用script实现查询List大小
- hbuildx中夜神模拟器的配置以及热更新
- Distributed system: what, why, how
猜你喜欢
随机推荐
LevelDB源码解读-SkipList
leetcode刷题:二叉树05(翻转二叉树)
leetcode刷题:二叉树04(二叉树的层序遍历)
leetcode刷题:二叉树06(对称二叉树)
Tcp- simple understanding of three handshakes and four waves
Evolution of MySQL database architecture
透过JVM-SANDBOX源码,了解字节码增强技术原理
PPt 教程,如何在 PowerPoint 中将演示文稿另存为 PDF 文件?
Ppt tutorial, how to save a presentation as a PDF file in PowerPoint?
架构实战营 - 第 6 期 模块九之毕业设计
Pytest multi process / multi thread execution test case
统计遗传学:第三章,群体遗传
[microservice openfeign] use openfeign to remotely call the file upload interface
[book club issue 13] packaging format of video files
Confession code collection, who says program apes don't understand romance
Balance between picture performance of unity mobile game performance optimization spectrum and GPU pressure
There is a problem that the package cannot be parsed in the like project
How to add custom API objects in kubernetes (1)
微信公众号无限回调授权系统源码
分布式系统:what、why、how