I wrote this column because I recently wanted to reorganize my front-end knowledge systematically. I will try to write some business related tips and front-end knowledge of the key content, core ideas.

preface

In fact, I talked about Eventloop in browsers in previous articles. However, eventloop in NodeJs is different from browser eventloop. Mastering EventLoop is an important skill for anyone who writes NodeJS. Because it means that not only do you know how to write JS, but you also know how to write NodeJs.

Why eventLoop?

We know that the essence of NodeJs is to take the browser’s V8 and run it on the operating system, thus taking the browser’s event loop. But why the eventloop?

For historical reasons, JS was designed as a simple language for manipulating the DOM on a page (everyone has heard the story that JS was designed in 10 days). For this purpose, we certainly want js to be as simple and light as possible. How light? Light to JS rendering engines are run in a thread.

The problem is that if you’re running JS on a thread, when the code is linear, of course there’s no problem. But on a page, we need user interaction, and those interactions happen without knowing why. What about js? If I have running code in front of me, how does the program react when a user interaction comes in? If the user’s interaction is processed first, the original program is suspended (that is, blocked). To avoid this blocking, JS uses a message queue to store this user interaction. Wait for all programs to run, then go to the message queue to fetch the interaction event, and then execute. That solves the blocking problem.

Eventloop for the browser

We all know that when a browser is browsing a page, user interaction is always possible in order to respond to the user immediately. Js will not close, it will continue to loop. Roughly as follows:

Fetch task from message queue > Execute task > Execute task > Complete > Fetch task from message queue >....Copy the code

Of course, as we discussed earlier in the event loop article, in order to categorize different asynchronous tasks, there is actually a distinction between macro and micro tasks in the event loop. Their execution is roughly as follows

To the message queue with task - > micro tasks -- -- -- -- > > micro task has been completed to the message queue with macro task - > macro mission -- -- -- -- > > macro task has been completed to the message queue with task - >...Copy the code

The eventloop NodeJs

NodeJs’s event loop is similar in general to that of the browser, but nodeJs distinguishes between different macro tasks in different periods. Here’s the official flow chart:

You can see that each event loop in nodeJs is divided into six specific periods, each of which uses a specified macro task. The microtask queue is then completed before macro tasks are executed for each period.

The overview

timers Performed by thesetTimeout()setInterval()Triggered callback
pending callbacks Perform I/O callbacks deferred until the next iteration of the loop
idle, prepare For internal use only, developers can ignore it
poll Retrieve new I/O events; Perform I/O related callbacks (will perform almost all callbacks except for close callbacks and timers schedulers and setImmediate() callback, which will block at this stage at the appropriate time)
check performsetImmediate()
close callbacks Such assocket.on(‘close’, …)

In fact, from the above table, we already have a clear idea of the execution order of the event loop mechanism. But you might still have some questions. Let’s talk about it in more detail.

pending callbacks

This phase deals with callbacks that should have been executed in the last event loop due to an operating system error. Some TCP errors, for example. So this part, which the developer can’t do on his own initiative, is the fault tolerance mechanism of NodeJs.

check

Similarly, setImmediate is a NodeJs-specific API that instantly creates an asynchronous macro task. Nodejs also sets up a check period in the event loop, where setImmediate’s callbacks are performed exclusively. Even if you keep generating setImmediate callbacks during this period, eventLoop will take precedence.

close callbacks

This period handles closing events such as socket.on(‘close’,…). This ensures that all tasks are completed before some communication is completed.

Microtasks are in eventloop

Let’s start by reviewing the differences between browsers and NodeJS:

Macro task:

task The browser Node
I/O
setTimeout
setInterval
setImmediate
requestAnimationFrame

Micro tasks:

task The browser Node
process.nextTick
MutationObserver
Promise.then catch finally

As you can see, process.nexttick is a microtask specific to NodeJS. Not only that, but process.nexttick () takes precedence over all microtasks, and every time the list of microtasks is cleared, process.nexttick () is executed first.

The variance

Not only are there differences in the type of tasks, but there are also differences in the execution of the two environments. When executing tasks on the browser, you need to make sure that the microtask queue is finished before each macro task is executed. On NodeJS, each period is preceded by ensuring that the microtask queue is finished. In other words, if in the timer period, all setTimeout and setInterval macro tasks will be executed first. After performing the microtask, we move on to the next period.

Note: The above execution rules are prior to the V11 version of NodeJS. After version 11, nodeJS execution output is the same as that of the browser.

setImmediate() vs setTimeout()

The sequence of setImmediate() and setTimeout() does not vary, meaning that if you do the following code over and over again, the result may not be the same each time.

setTimeout(() => {
  console.log('timeout');
}, 0);

setImmediate(() => {
  console.log('immediate');
});
Copy the code

The reason is that the program’s handling of time is flawed. The time set in the setTimeout method may not be accurate. Also, when the callback is triggered, there is no way to determine which period the event cycle is in, either timer or check. So there will be different results.

conclusion

Eventloop is one of the most important parts of the JS execution mechanism, and for NodeJs, eventloop has more room to operate. Because it is subdivided into periods, it is possible to further refine the logic. Also, with nextTick’s highest priority, you can write code that isn’t possible in a browser. So for developers who are deep into NodeJs, EventLoop is often the first step to see what new people understand about NodeJs.

reference

Nodejs.org/en/docs/gui…

www.jianshu.com/p/deedcbf68…

www.cnblogs.com/nanianqimin…