Developer's javascript Attainments depend on right 【 dynamic 】 and 【 asynchronous 】 The level of understanding of these two words .



One . An interview question about asynchronous knowledge

The title is like this , Write the output of the following code :
setTimeout(() => { console.log(1) }, 0) new Promise((resolve, reject) => {
console.log(2) for (let i = 0; i < 10000; i++) { i === 9999 && resolve() }
console.log(3) }).then(() => { console.log(4) }) console.log(5)
If you haven't delved into asynchronous queues in detail , The probability of a correct answer is very low . The investigation point of the topic is very clear , namely javascript One of the core features of 【 asynchronous 】, After understanding the principle , You'll understand
javascript It is claimed in “ No obstruction ” It's not entirely true , Through some small ways, we can make setTimeout( )
The callback of can never be executed , Although it seems that there is no obvious practical value other than meeting the demand of trickery .

Yes Event Loop Understanding of , What brings developers is more fine-grained control over the entire code life cycle , Although relying on SPA You rarely use them in the development of frameworks .

Two . Event Loop The principle of



( The above image is from the recommended blog post below )

【 Highly recommended articles 】:

https://github.com/nswbmw/node-in-debugging/blob/master/3.6%20Event%20Loop.md
<https://github.com/nswbmw/node-in-debugging/blob/master/3.6%20Event%20Loop.md>

It's not that the author is lazy and doesn't want to write this section , But after reading this tutorial , I think that unless it's a deeper analysis libuv The principle of , Otherwise, just understand Event
Loop for , I don't think it can be clearer than this one .

Three . Analysis of the last question

From simple to complex, the 6 Questions for readers to self check , It's very sweet , In this paper, the last question for some explanation . You'll find that if you understand Event Loop
After the basic principle of , Analyzing this kind of code is basically a 【 Cloze Test 】 The process of .

The title is as follows :
setImmediate(() => { console.log(1) setTimeout(() => { console.log(2) }, 100)
setImmediate(() => { console.log(3) }) process.nextTick(() => { console.log(4)
}) }) process.nextTick(() => { console.log(5) setTimeout(() => { console.log(6)
}, 100) setImmediate(() => { console.log(7) }) process.nextTick(() => {
console.log(8) }) }) console.log(9)
Topic analysis :

In order to facilitate the analysis , Block the code first :



Put the code block into the event loop :



analysis :

It is necessary to explain here Fn2 Location of , It is not explicitly mentioned in the article that when the synchronous code is executed, it will first go through the asynchronous queue Tick stage , As far as the diagram is concerned , Each macro task stage is checked between Tick
queue ( You can also think of it as checking every time the call stack of a function is cleared Tick queue ), that Fn2 It's easy to understand . In order to facilitate the analysis , take console.log(n)
The relevant method is called cln.

Let's take a look at when executing to Fn2 What happened when :


analysis :

Tick In queue process.nextTick( ) Callbacks are added directly Tick queue ( Here we can implement the blocking event loop mentioned in the title ). Let's talk about it in another way CL6
This callback , It has a binding on it 100ms Timer for , In the follow-up Timers and IO Polling Will check whether the countdown has expired , Execute when you arrive , Wait for the next time Timers or IO
Polling Stage review . From the above example , delay 100ms Of CL6 In the absence of other interference, it is almost certain that N individual event loop It was executed later .

Let's split it up in the same way Fn1:



analysis :

CL6 than CL2 Start timing first , So the countdown 100ms arrive earlier than , Of course, this is N After a loop of events .

So you can see the output from the above sequence :9 5 8 1 7 4 3 6 2

【 Thinking questions 】:

Plus a thought question , If in the above example CL6 and CL2 All the delays are 0, What was the result ?

Four . requestAnimationFrame

requestAnimationFrame() A lot of times it's brought to you setTimeout()
For comparison , this API It is designed to achieve high performance frame animation in browser environment , Its main purpose is to make the redrawing of the browser match the refresh rate of the display device without unnecessary performance overhead , Common display device refresh rate is
60Hz
, You are equal to every 1000/60≈16.7ms You can only look at the screen , The information obtained is based on the visual persistence of these discrete images , If the animation element moves too much during the time you look at the screen , It looks like it's going to be one card at a time , That's what I usually say “ Frame loss ”, from Event
Loop From the perspective of , It is approximately understood as setTimeout(fn, 1000/ Refresh rate ) That's fine .

edit / Fish in search of water
This article was first published in Huawei cloud community : Link to original text
<https://bbs.huaweicloud.com/blogs/04d6b508b7c611e89fc57ca23e93a89f>