Developerjavascript Attainment depends on being right【 dynamic】 and【 asynchronous】 The level of understanding of these two words.

One. An interview question to investigate asynchronous knowledge

The title is like this, The output of the following code is required:
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 studied asynchronous queues in detail, Very low probability of correct answer. The investigation point of the topic is very clear, Namelyjavascript One of the core features of【 asynchronous】, After understanding the principle, You will understand
javascript Claimed“ Non blocking” It's not entirely true. There are some small ways to makesetTimeout( )
's callback can never be executed, Although this seems to have little practical value other than satisfying the demand for trickery.

YesEvent Loop Understanding, What we bring to developers is more sophisticated control over the entire life cycle of the code. Although it depends onSPA You hardly use them in the development of frameworks..

Two. Event Loop Principle

( The picture above comes from the following recommendation)

【 Highly recommended articles】:

It's not that I'm lazy and don't want to write this section. But after reading this tutorial,, I think it's not the bottom linelibuv Principle, Otherwise, just understandEvent
Loop For, I don't think it's any clearer than this one..

Three. Analysis of the last question

From simple to complex6 Questions for self inspection, It's very kind, In this paper, the last question is explained.. You will find that just understandEvent Loop
After the basic principle of, Analyzing this kind of code is basically a【 Cloze Test】 Process.

Topics are 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)
Title Analysis:

For the convenience of analysis, Code block first:

Put code block into event loop:


It is necessary to explain hereFn2 Location, It is not explicitly mentioned in the article that when the synchronous code is executed and enters the asynchronous queue, it will first experienceTick stage, As far as the diagram is concerned, Check between each macro task stageTick
queue( You can also understand that every time the function's call stack is cleared, it will be checked once.Tick queue), thatFn2 The execution time sequence of is well understood.. For the convenience of analysis, takeconsole.log(n)
The relevant method is calledcln.

Let's take a look at when theFn2 What happened:


Tick Queueprocess.nextTick( ) Callback will be added directlyTick queue( You can implement the blocking event loop mentioned at the beginning of this article.). Another pointCL6
This callback, It's bound with a100ms Timer, Follow upTimers andIO Polling China will check whether the countdown expires, When it comes, it will be implemented, Wait for the next time before you arriveTimers orIO
Polling Stage recheck. From the above example, delay100ms OfCL6 Almost certainly in the absence of other interferenceN individualevent loop Only later.

In the same way, split it up.Fn1:


CL6 thanCL2 Start timing, So the countdown100ms arrive earlier than, Of course, this isN After an event cycle.

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

【 Thinking questions】:

Plus a thought question, If in the above exampleCL6 andCL2 The delays are0, What's the result?

Four. requestAnimationFrame

requestAnimationFrame() A lot of the time it's taken withsetTimeout()
Contrast, thisAPI It is designed to achieve high-performance frame animation in browser environment, Its main purpose is to make the browser redraw match the refresh rate of the display device without unnecessary performance overhead. The common refresh rate of display device is
, Equivalent to every1000/60≈16.7ms Only one look at the screen, All the information we get is based on the visual persistence of these discrete images. So if the pixels of the animation elements are shifted too much in the time interval between you and the screen,, It looks like it's going to be one card at a time. That's what we usually say.“ Drop frames”, fromEvent
Loop From the point of view, Take it approximately assetTimeout(fn, 1000/ Refresh rate) That's all right..

edit/ Fish for water
This article first appeared in Huawei cloud community: Original link