当前位置:网站首页>JS asynchronous mechanism
JS asynchronous mechanism
2022-06-23 02:57:00 【User 1349575】
One 、 Synchronous and asynchronous
1. Sync
If when the function returns , The caller can get the expected result ( That is to get the expected return value or see the expected effect ), So this function is synchronous .
2. asynchronous
If when the function returns , The caller hasn't been able to get the expected result , It needs to be obtained by certain means in the future , So this function is asynchronous .
Two 、 Single thread and multi thread
javascript It's a single thread operation , Who are the time-consuming operations entrusted to ?
javascript It's actually a language , Whether it is single thread or multi-threaded should be combined with the specific running environment .javascript Is usually run in a browser , Specific reasons JS Engine parsing and running .
1、 browser
The popular browsers at present are :Chrome、FireFox、IE、Opera、Safari. Browser kernel is multithreaded .
A browser usually has several resident threads :
- Rendering engine threads : seeing the name of a thing one thinks of its function , This thread is responsible for rendering the page
- JS Engine threads : be responsible for JS Analysis and execution of
- Timing trigger thread : Handle timing events , such as setTimeout、setInterval
- Event trigger thread : Handle DOM event
- asynchronous http Request thread : Handle http request
It should be noted that , Rendering threads and JS Engine threads cannot run at the same time . When the rendering thread is executing the task ,JS Engine threads will be suspended . because JS Can operate DOM, If in rendering JS Processed DOM, The browser may be at a loss .
2. JS engine
Usually when it comes to browsers , We'll talk about two engines : Rendering engine and JS engine . The rendering engine is how to render pages ,Chrome、Safari、Opera It's using Webkit engine ,IE It's using Trident engine ,FireFox It's using Gecko engine . Different engines have different implementation effects on the same style , This leads to the browser compatibility problem which is often criticized .
JS The engine can be said to be JS virtual machine , be responsible for JS Code parsing and execution . It usually includes the previous steps :
- Lexical analysis : Decompose the source code into meaningful participles
- Syntax analysis : Parse the idiom tree with a parser
- Code generation : The code that the sound field machine can run
- Code execution
Different browsers JS The engines are different ,Chrome It's using V8,FireFox It's using SpiderMonkey,Safari It's using JavaScriptCore,IE It's using Chakra.
Reason why JavaScript A single thread , It's because the browser only has one open at runtime JS Engine threads to parse and execute JS. Then why is there only one engine ? If there are two threads to operate at the same time DOM, Is the browser at a loss again .
therefore , although JavaScript It's single threaded , But the browser is not single threaded . some I/O operation 、 Timer timing and event monitoring (click,keydown) And so on are done by other threads provided by the browser .
3、 ... and 、 Message queues and event loops
Through the above understanding , We can know that in fact JavaScript through JS The engine thread interacts and cooperates with other threads in the browser to achieve asynchrony . But when does the callback function add to JS Execution in engine thread ? What is the order of execution ?
The explanation of all this continues with a continued understanding of message queues and event loops .
Once an asynchronous task has a response, it is pushed into the queue . Such as the user's click event 、 The browser receives a response from the service and setTimeout Events to be executed in , Each asynchrony is associated with a callback function .
JS Engine threads are used to perform synchronization tasks in the stack , When all synchronization tasks are completed , Stack cleared , Then read a pending task in the message queue , And push the relevant callback function into the stack , A single thread starts to perform a new synchronization task .
JS The engine thread reads tasks from the message queue in a continuous loop , Every time the stack is emptied , Will read new tasks in the message queue , If there is no new task , Will wait , Until there's a new mission , This is called the event cycle .
After the asynchronous task is initiated , from AJAx Threads perform time-consuming asynchronous operations , and JS The engine thread continues to perform other synchronization tasks in the heap , Until all asynchronous tasks in the heap have been executed . then , Take messages out of the message queue in order as a synchronization task JS Execution in engine thread , that AJAX The callback function will be executed at a certain moment .
Four 、 example
setTimeout(function(){
for(var i = 0; i < 100000000; i++){}
console.log('timer a');
}, 0)
for(var j = 0; j < 5; j++){
console.log(j);
}
setTimeout(function(){
console.log('timer b');
}, 0)
function waitFiveSeconds(){
var now = (new Date()).getTime();
while(((new Date()).getTime() - now) < 5000){}
console.log('finished waiting');
}
document.addEventListener('click', function(){
console.log('click');
})
console.log('click begin');
waitFiveSeconds();边栏推荐
- Learning notes of recommendation system (1) - Collaborative Filtering - Theory
- 862. triple sorting
- Apache Druid's engineering practice in shopee
- Some people are crazy, others are running away, and open source software is both hot and cold
- An article shows you the difference between high fidelity and low fidelity prototypes
- Reading redis source code (VI) multi threading of redis 6.0
- How to gracefully solve the problem of platform font adaptation
- The priority supplier field in the purchase information record of SAP mm primary level
- Deep analysis of time complexity
- 5. concept of ruler method
猜你喜欢

Soft exam information system project manager_ Information system comprehensive testing and management - Senior Information System Project Manager of soft test 027

Soft exam information system project manager_ Contract Law_ Copyright_ Implementation Regulations - Senior Information System Project Manager of soft exam 030

5. concept of ruler method

C language series - Section 4 - arrays

8. greed

How to store, manage and view family photos in an orderly manner?

6. template for integer and real number dichotomy

Spark broadcast variables and accumulators (cases attached)
What is sitelock? What is the function?

Vulnhub DC-5
随机推荐
Goframe framework (RK boot): rapid configuration of server CORS
Handlebars dynamic adjustment
HTTP cache
Summary of website navigation design and website link optimization
Goframe framework (RK boot): fast implementation of CSRF verification
Line to line interviewer | one side of ByteDance
Supervisor multi process management exception automatic restart visual management
Vulnhub DC-5
Qingdao stadium has made headlines again, but it has nothing to do with sports
Docker builds MySQL master-slave
2022-01-28: for example, {5, 3, 1, 4} all number pairs are: (5,3), (5,1)
C language series - Section 4 - arrays
Reading redis source code (VI) multi threading of redis 6.0
Exploit format string vulnerability in CDE
Reading redis source code (II) underlying data structure
January 31, 2022: Maze III. There is a ball in the maze of open spaces and walls. ball
Transformation solution of digital intelligent supply chain platform for project management in engineering industry
February 3, 2022: a group of people (two or more) want to meet at the same place
Im web demo invite end hang up error avoidance
[data preparation and Feature Engineering] data cleaning