当前位置:网站首页>Operating principle of JS core EventLoop
Operating principle of JS core EventLoop
2022-06-13 02:46:00 【Zeng Qiang】
Catalog
Javascript The runtime environment for
extend : Macro task and micro task
background
Javascript The runtime environment for
Javascript The runtime environment of is generally referred to as the browser or Node.js. Generally speaking Javascript The runtime environment is used in addition to parsing and executing JS Code Javascript engine , It also includes WebAPI, Thread pool , Task queue ,EventLoop wait . When these components are combined, they are Javascript Provide an asynchronous and responsive environment .
Synchronous and asynchronous
Sync : You can only do one thing at a time .Javacript The engine is a single thread . Responsible for interpreting and executing JavaScript Code this means you can only do one thing at a time . It's like a one-way street , Only one car at a time , It is easy to cause blockage .
A single thread can only do synchronous operations , So how to solve the problem caused by blocking ? Asynchronous programming .Javascript The runtime provides a EventLoop Event cycle model for , To handle asynchronous operations . Now I will start from EventLoop Structure and code case of , Two aspects of analysis EventLoop working principle .
EventLoop Operating mechanism
overview :EventLoop stay Javascript Runtime ( Browser environment ) The location of .
Call stack: Call Stack .JS Execute one line of code at a time ,
WebAPI: When the call stack encounters setTimeout(callback,timeout)API When , The timer that will be given to the browser counts down , After time , Will be able to callback Push the callBackQueue in .
CallbackQueue:callBackQueue Used to save callback functions
EventLoop: The event circulator periodically detects whether the call stack is empty , If the call stack is empty , It will put callbackQueue Callback out of the queue , Put it into the call stack to execute .
RenderQueue: Render event queue .EventLoop Priority will be given to the... In the rendering queue callback.
The code that calls the stack is in JS Executed in a single thread . therefore callback And call stack if the execution time is too long , It will cause the process of page rendering to be blocked .
GUI In process GUI The rendering thread is responsible for page rendering , But the same thing JS Is mutually exclusive , Both pass EventLoop signal communication .
case analysis
function pipe(){
console.log('do easy sth... 1');
setTimeout(function (){
console.log("do hard sth... 2")
}, 1000)
setTimeout(function (){
console.log("do hard sth... 3")
}, 1000)
setTimeout(function (){
console.log("do hard sth... 4")
}, 1000)
setTimeout(function (){
console.log("do hard sth... 5")
}, 1000)
setTimeout(function (){
console.log("do hard sth... 6")
}, 1000)
console.log('do easy sth... 7')
}
// Output :1,7,2,3,4,5,6
Why the above code output is not 1,2,3,4,5,6,7? This is because ,JS Execute the code in the call stack first , therefore 1 ,7 Will print first , secondly setTimeout Will put it callback Put it in Callback The queue is waiting to be EventLoop Dispatch . and EventLoop Only when the call stack is empty , Will be scheduled in turn CallBack queue . So we should try our best to ensure UI Rendering is performed forward , And the call stack should not do time-consuming operations .
extend : Macro task and micro task
Micro task :Promise Every time you call then() when , Registered tasks .
Macro task :callback Every frame in the queue or call stack is a macro task , The current micro task queue will be executed immediately after the macro task is executed , Then you can switch to the rendering thread to perform the page rendering task .
The relationship between them : Macro task -> Micro task -> Rendering tasks --> Macro task ...
summary
EventLoop yes GUI The common asynchronous programming model in programming ,Android It is also in development . The call stack is like a pipeline , Specializing in the production of products , Encounter tasks that require time-consuming operations , Just throw it to the product polishing Department (WebAPI), The product polishing department finishes the time-consuming task , The result of the mission , Put in a queue , hand EventLoop This dispatcher dispatches ,EventLoop When the monitoring assembly line is free, it will rotate training callback queue , hold CallBack The time-consuming task results of the queue are displayed , Let the assembly line continue to work .
Reference link
边栏推荐
- Image classification system based on support vector machine (Matlab GUI interface version)
- MySQL index
- nn. Conv2d and nn Convtranspose2d differences
- Ijkplayer source code --- decode
- Traverse the array and delete an element until it is deleted
- Prometheus node_ Exporter installs and registers as a service
- How to destroy a fragment- How to destroy Fragment?
- Opencvshare4 and vs2019 configuration
- 04 route jump and carry parameters
- Perfect square
猜你喜欢
[reading point paper] yolo9000:better, faster, stronger, (yolov2), integrating various methods to improve the idea of map and wordtree data fusion
Detailed explanation of UCI datasets and their data processing (with 148 datasets and processing codes attached)
Linked list: the first coincident node of two linked lists
[data analysis and visualization] key points of data drawing 12- importance of chart notes
[reading papers] deep learning face representation from predicting 10000 classes. deepID
[reading some papers] introducing deep learning into the public horizon alexnet
Introduction to facial expression recognition system - Technical Paper Edition
Logiciel professionnel de gestion de base de données: Valentina Studio Pro pour Mac
[reading papers] transformer miscellaneous notes, especially miscellaneous
[data and Analysis Visualization] D3 introductory tutorial 1-d3 basic knowledge
随机推荐
Leetcode 926. Flip string to monotonically increasing [prefix and]
Graduation project - campus old thing recycling system based on stm32
OpenCVSharpSample04WinForms
JS multiple judgment writing
Branch and bound method, example sorting
Detailed explanation of handwritten numeral recognition based on support vector machine (Matlab GUI code, providing handwriting pad)
CDN single page reference of indexbar index column in vant framework cannot be displayed normally
Example 4 linear filtering and built-in filtering
[reading papers] deep learning face representation from predicting 10000 classes. deepID
Using binary heap to implement priority queue
Redirection setting parameters -redirectattributes
Uni app Foundation
[reading papers] transformer miscellaneous notes, especially miscellaneous
数仓笔记|针对客户维度建模需要关注的5个因素
[data analysis and visualization] key points of data drawing 9- color selection
[data and Analysis Visualization] D3 introductory tutorial 1-d3 basic knowledge
Ijkplayer source code - choose soft decoding or hard decoding
Special topic I of mathematical physics of the sprint strong foundation program
遍历数组,删除某元素,直到删除为止
[data analysis and visualization] key points of data mapping 7- over mapping