current position:Home>Analysis of operation mechanism of new generation JavaScript
Analysis of operation mechanism of new generation JavaScript
2021-08-27 08:34:26 【Xiao Cheng】
This article has participated in the third phase of nuggets creators training camp 「 Topic writing 」 Track , View details : Project digging | The third phase of the creator training camp is under way ,「 Write 」 Personal influence .
Hello everyone , I'm Xiao Cheng's classmate , A prospective sophomore front-end enthusiast
This article will take you to learn and understand JavaScript Operating mechanism
May you be true to yourself , love your life
introduction
In some interviews , We may be asked such questions
Briefly JavaScript Operation mechanism of ?
You may also be asked such code
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 ')
});
Copy code
Although these look profound and complex , But if you understand JavaScript Operation mechanism of , These problems can be solved one by one
The outline of this article is attached first , This article will start from this Three aspects Parse JavaScript Operation mechanism of
First of all, let's talk about JavaScript The single thread
1. Why single thread ?
as everyone knows ,JavaScript It is a single-threaded language , It has also brought a lot of criticism , So single thread is so unbearable , Why not design it as multithreaded ?
In fact, this problem appears in JavaScript Of Application scenarios On , We usually use JavaScript To operate DOM Elements , This is no problem now . But let's think about it , If JavaScript Became a multithreaded language , What will happen then ?
Imagine the scene below
a section JS Code Delete DOM Elements , a section JS Code change DOM Element style , They were executed together , What will happen ?
Let's not talk about what the browser should do , I don't even know how to deal with , Then the browser will crash ...
To avoid such a situation , JavaScript Designed as a single threaded language
Single thread means , Only one task can be performed at a time , Other tasks need to wait in line
But in order to have multithreading function , There have been many attempts
stay HTML5 In the proposed web worker
standard , It provides a complete set of API To allow outside the main thread To execute another thread , But this Doesn't mean the JavaScript Since then, I have the ability of multithreading , At the same time, we can't use it to operate DOM Elements .
stay JavaScript There is also a unique implementation mechanism , It divides the tasks in the main thread into synchronous tasks and asynchronous tasks
2. Why do I need to be asynchronous ?
In order to solve the problem of code blocking caused by single thread
JS It's single threaded , We can imagine a ticket window , There are many people waiting in line at the window for business , and JS You can only process one by one , If a customer has a lot of needs , It takes a long time to handle business , Then the rest of the team will have to wait , It's equivalent to code blocking , Browser Feign death , Wait for the code to execute
Therefore, we have the concepts of synchronous task and asynchronous task
It is necessary to distinguish , Separate those who have been doing business for a long time , Wait until other customers are processed before unified processing
Synchronous tasks and asynchronous tasks are explained in this way
- Synchronization task : Is a task queued on the main thread , Only the previous task was completed , To perform the next task , for example :
console.log
- Asynchronous task : Do not enter the main thread 、 Handling through event loop mechanism , Register the callback function in the task queue and finally get the result , for example :
setTimeout
Learned what synchronization is , What is asynchronous , Let's have a very simple topic
console.log(1);
setTimeout(()=>{console.log(2);},0)
console.log(3);
Copy code
Results output 1 3 2
as a result of setTimeout
It's an asynchronous task , It needs to be executed after synchronous code execution
Next, let's talk about the core of the operating mechanism : The event loop
3. The event loop
First, we use a diagram to understand the event loop
Its operation mechanism is as follows :
- All synchronization tasks are performed on the main thread , Form an execution stack , That is, the blue arrow in the figure above indicates
- There is an asynchronous task queue outside the main thread ( The red arrow ), Will wait until the asynchronous task After returning the result Put it in Task queue
- When the stack code in the main thread is executed , That is, the synchronization task is completed , will Start reading Task queue code , Then put it into the execution stack to execute
- Keep repeating the above three steps , This is the event loop
If you use graphics , It's the one in the picture above Three black arrows , Connected closed loop
in other words : As long as the main thread execution stack is empty , Will read the task queue , The process is cyclical , This mechanism is called event loop
Understand the event loop , Let's make a simple upgrade to the previous question
console.log(1);
setTimeout(()=>{console.log(2);},0)
setTimeout(()=>{console.log(3);},1000)
setTimeout(()=>{console.log(4);},0)
console.log(5);
Copy code
Output this time 1 -- 5 -- 2 -- 4 -- 3
Someone might be right 3
I have doubts about the output of , First, timers are asynchronous tasks , Will be put into the asynchronous task queue first , Need to wait for asynchronous tasks After returning the result , Then put the callback function into the task queue , Wait for the main thread to execute , therefore ,2 and 4 Will be in 3 Output before
4. Asynchronous task queue details
Common events that will be put into the asynchronous task queue
- DOM event
- Promise
- Ajax request
setTimeout
andsetlnterval
- Upload files
As for the time to join the asynchronous task queue , It depends on the current asynchronous task , Not to say that Get the asynchronous task and add it directly to the task queue , Wait until the current asynchronous task is completed and the result is returned , Just put it in the task queue
take setTimeout
Come on , Is the need to Wait for the timing to end Then add the callback to the task queue
It can also be understood in combination with the following figure
Understand the task queue , We need to talk again about asynchronous tasks , Macro tasks and micro tasks subdivided
5. Macro task and micro task
There can be multiple queues of macro tasks , There is only one microtask queue
So what is a macro task , What are micro tasks ?
- The macro tasks are :HTML analysis 、 Mouse events 、 Keyboard events 、 Network request 、 Execution thread js Code and timer
- Micro task :
promise.then
,DOM Rendering ,async
,process.nextTick
How is it executed ?
-
When the synchronization task in the execution stack is completed , Do the micro task first
-
After the execution of the micro task queue , Will read macro tasks
-
During the execution of the macro task , Encounter microtask , Then join the micro task queue
-
After the macro task is executed , Read the micro task queue again , In turn, cycle
Draw a picture to help understand
Summarize in a simple sentence : Micro tasks are always executed before macro tasks are executed
Particular attention Yes. : Because the code entry is a script
label . therefore , Global tasks are macro tasks
6. actual combat
After knowing so much , Let's look at the classic interview questions
console.log("1");
setTimeout(function () {
console.log("2");
new Promise(function (resolve) {
console.log("3");
resolve();
}).then(function () {
console.log("4");
});
});
new Promise(function (resolve) {
console.log("5");
resolve();
}).then(function () {
console.log("6");
});
setTimeout(function () {
console.log("7");
});
setTimeout(function () {
console.log("8");
new Promise(function (resolve) {
console.log("9");
resolve();
}).then(function () {
console.log("10");
});
});
new Promise(function (resolve) {
console.log("11");
resolve();
}).then(function () {
console.log("12");
});
console.log("13");
Copy code
The answer is :1 -- 5 -- 11 -- 13 -- 6 -- 12 -- 2 -- 3 -- 4 -- 7 -- 8 -- 9 -- 10
The first cycle
- From the global task portal , First Print journal
1
- Encounter macro task
setTimeout
, To the asynchronous processing module , Write it down assetTimeout1
- Meet again promise object , Print journal
5
, takepromise.then
Join the micro task queue , Remember to dop1
- Meet again
setTimeout
To the asynchronous processing module , Write it down assetTimeout2
- Meet again
setTimeout
To the asynchronous processing module , Write it down assetTimeout3
- encounter promise object , Print log
11
, takepromise.then
Join the micro task queue , Remember to dop2
- Encountered print statement , Print log directly
13
A total of... Are printed in this cycle :1 -- 5 -- 11 -- 13
Current cycle result
The second cycle
- First execute the micro task queue
p1
andp2
, fifo , Print first6
Re print12
- Micro task event processing completed , Start performing macro tasks
setTimeout1
- Encountered print statement , Print log directly
2
- Meet again promise object , Print log
3
, takepromise.then
Join the micro task queue , Remember to dop3
The second cycle ends
The current running diagram is
The third cycle
- First execute the micro task queue , Print log
4
- Micro task processing completed , Execute macro task
setTimeout2
- Encountered print statement , Direct output
7
The cycle ends
The fourth cycle
- The micro task queue is empty , Execute macro task
setTimeout3
- Encountered print statement , Print log
8
- encounter promise object , Execute the print statement , Print
9
- take
promise.then
Join the micro task queue Remember to dop4
The fifth cycle
- First, empty the micro task queue , Execute the print statement , Print
10
- completion of enforcement
That's about JavaScript The whole content of the operating mechanism , I hope I can get something
Thank you very much for reading , Your comments are welcome , If you have any questions, please point out , thank you !
copyright notice
author[Xiao Cheng],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827083424490r.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich