当前位置:网站首页>JS engine loop mechanism: synchronous, asynchronous, event loop
JS engine loop mechanism: synchronous, asynchronous, event loop
2022-04-23 04:53:00 【Crazy_ GirlLL】
The original author :https://segmentfault.com/a/1190000012806637
In depth understanding of JS Execution mechanism of engine
- 1. Soul three asked : JS Why single threaded ? Why do I need to be asynchronous ? How does single thread realize asynchrony ?
- 2.JS Medium event loop(1)
- 3.JS Medium event loop(2)
- 4. say something setTimeout
First , Please bear in mind. 2 spot :
(1) JS It's a single-threaded language
(2) JS Of Event Loop yes JS Implementation mechanism of . Deepen understanding JS Implementation , It's like getting to know JS Inside event loop
1. Soul three asked : JS Why single threaded ? Why do I need to be asynchronous ? How does single thread realize asynchrony ?
The emergence of Technology , Are closely related to the application scenarios in the real world .
alike , Let's combine the real scene , To answer these three questions
(1) JS Why single threaded ?
JS Originally designed for use in browsers , So imagine , If in the browser JS It's multi-threaded .
Scene description :
So now there are 2 Threads ,process1 process2, Because it is multithreaded JS, So they treat the same dom, Operate at the same time
process1 Deleted the dom, and process2 Edited the dom, At the same time 2 A contradictory order , How on earth should the browser execute ?
Think so ,JS Why is it designed as a single thread should be easy to understand .
(2) JS Why do I need to be asynchronous ?
Scene description :
If JS There is no asynchrony in , Only from top to bottom , If the previous line takes a long time to parse , Then the following code will be blocked .
For users , Blocking means " stuck ", This leads to a very poor user experience
therefore ,JS There is asynchronous execution .
(3) JS How does single thread realize asynchrony ?
since JS It's single threaded , Can only execute on one thread , How to realize asynchrony ?
It's a loop of events through (event loop), I understand event loop Mechanism , I understand. JS Implementation mechanism of
2.JS Medium event loop(1)
example 1, Observe its execution order
console.log(1)
setTimeout(function(){
console.log(2)
},0)
console.log(3)
The result of the operation is : 1 3 2
in other words ,setTimeout The function in does not execute immediately , It was delayed for some time , When certain conditions are met , To execute it , This kind of code , We call it asynchronous code .
therefore , Here we first know JS A sort of classification in , Is to divide the task into : Synchronous tasks and asynchronous tasks
Picture description
According to this classification :JS The implementation mechanism of the system is
- First judgement JS Synchronous or asynchronous , Synchronization goes into the main thread , Asynchrony goes into event table
- Asynchronous task in event table Register function in , When the trigger conditions are met , Be pushed in event queue
- The synchronization task is executed all the time after entering the main thread , Until the main thread is idle , To go to event queue To see if there are any asynchronous tasks that can be performed , If so, push it into the main thread
The above three steps are executed in a cycle , This is it. event loop
So the example above , Can you describe the sequence of its execution ?
console.log(1) It's a synchronization task , Put it in the main process
setTimeout() It's an asynchronous task , Be put in event table, 0 Seconds later, it is pushed event queue in
console.log(3 It's a synchronization task , Put it in the main route
When 1、 3 After the control bar is printed , Main thread to event queue( Event queue ) Check to see if there are executable functions , perform setTimeout The function in
3.JS Medium event loop(2)
therefore , Above about event loop It's me. JS Understanding of execution mechanism , Until I came across the following code
example 2:
setTimeout(function(){
console.log(' The timer is on ')
});
new Promise(function(resolve){
console.log(' Do it now for It's a cycle ');
for(var i = 0; i < 10000; i++){
i == 99 && resolve();
}
}).then(function(){
console.log(' perform then Function ')
});
console.log(' End of code execution ');
Try to follow , What we just learned above JS Execution mechanism to analyze
setTimeout It's an asynchronous task , Be put in event table
new Promise It's a synchronization task , Put into the main process , Print directly console.log(' Do it now for It's a cycle ')
.then The function in is Asynchronous task , Be put in event table
console.log(' End of code execution ') It's synchronization code , Put into the main process , Direct execution
therefore , The result is 【 Do it now for It's a cycle --- End of code execution --- The timer is on --- perform then Function 】 Do you ?
After personal execution , It turns out that's not the case , It is 【 Do it now for It's a cycle --- End of code execution --- perform then Function --- The timer is on 】
that , Is it the execution order of asynchronous tasks , Not in sequence , But there are other provisions ? in fact , According to the division of asynchronous and synchronous , Inaccurate .
And the exact division is :
- macro-task( Macro task ): Including the overall code script,setTimeout,setInterval
- micro-task( Micro task ):Promise,process.nextTick
According to this classification :JS The implementation mechanism of the system is
- Perform a macro task (script Holistic js Code ), If micro task is encountered in the process , Put it on the micro task 【 Event queue 】 in
- After the current macro task is completed , I'll check out the micro task 【 Event queue 】, And finish all the micro tasks in turn
Repeat above 2 step , combination event loop(1) event loop(2) , Is more accurate JS Implementation mechanism .
Try to follow the execution mechanism just learned , De analysis example 2:
First, execute script Macro task under , encounter setTimeout, Put it in the 【 queue 】 in
encounter new Promise Direct execution , Print " Do it now for It's a cycle "
encounter then Method , It's a micro task , Put it in the 【 In the queue 】
Print " End of code execution "
This round of macro task is completed , View this round of micro tasks , Found a then Functions in methods , Print " perform then Function "
Here we are , The current round event loop Complete .
In the next cycle , Execute a macro task first , Found macro task's 【 queue 】 There's one in it setTimeout The function in , Execution printing " The timer is on "
So the final order of execution is 【 Do it now for It's a cycle --- End of code execution --- perform then Function --- The timer is on 】
4. Talk about setTimeout
This paragraph setTimeout What does code mean ? We generally say : 3 Seconds later , Will execute setTimeout The function in
setTimeout(function(){
console.log(' Yes ')
},3000)
But this is not a rigorous statement , The exact explanation is : 3 Seconds later ,setTimeout The function in will be pushed into event queue, and event queue( Event queue ) The task in , Only when the main thread is idle .
So only satisfaction (1)3 Seconds later (2) Main thread idle , When simultaneously satisfied , Will 3 Execute the function in seconds
If the main thread executes a lot of content , Execution time exceeded 3 second , For example, it was implemented 10 second , So this function can only 10 Seconds later
版权声明
本文为[Crazy_ GirlLL]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220554364955.html
边栏推荐
- Innovation training (XI) airline ticket crawling company information
- List remove an element
- 洛谷P2731骑马修栅栏
- Programmers complain: I really can't live with a salary of 12000. Netizen: how can I say 3000
- Flink case - Kafka, MySQL source
- QPushbutton 槽函数被多次触发
- Informatics Aosai yibentong 1212: letters | openjudge 2.5 156: Letters
- Solve valueerror: argument must be a deny tensor: 0 - got shape [198602], but wanted [198602, 16]
- 《2021多多阅读报告》发布,95后、00后图书消费潜力攀升
- Unity3D 实用技巧 - 理论知识库(一)
猜你喜欢
View, modify and delete [database] table
Unity rawimage background seamlessly connected mobile
Small volume Schottky diode compatible with nsr20f30nxt5g
[database] MySQL single table query
Shanghai Hangxin technology sharing 𞓜 overview of safety characteristics of acm32 MCU
Recommended scheme for national production of electronic components for wireless charging
Recommended scheme of national manufactured electronic components for intelligent electronic scales
Eight misunderstandings that should be avoided in data visualization
[database] MySQL multi table query (I)
Sword finger offer: the median in the data stream (priority queue large top heap small top heap leetcode 295)
随机推荐
/etc/bash_ completion. D directory function (the user logs in and executes the script under the directory immediately)
负载均衡简介
独立站运营 | FaceBook营销神器——聊天机器人ManyChat
Innovative practice of short video content understanding and generation technology in meituan
[database] MySQL basic operation (basic operation ~)
Agile practice | agile indicators to improve group predictability
[database] MySQL single table query
拼了!两所A级大学,六所B级大学,纷纷撤销软件工程硕士点!
Eight misunderstandings that should be avoided in data visualization
【数据库】MySQL基本操作(基操~)
Better way to read configuration files than properties
Sword finger offer: push in and pop-up sequence of stack
C language: spoof games
Mac 进入mysql终端命令
Informatics Aosai yibentong 1212: letters | openjudge 2.5 156: Letters
MySQL time function query
unity摄像机旋转带有滑动效果(自转)
Programmers complain: I really can't live with a salary of 12000. Netizen: how can I say 3000
Leetcode009 -- search the target value in the array with binary search
Learning Android V from scratch - UI