Are there significant differences between the Chrome browser event loop and the host event loop?

Philip Roberts does a brilliant job explaining the browser event loop here , providing a clear explanation between the call stack, the event loop, the task queue, and then the β€œexternal” threads like webapis. My question is, are these parallel equivalent components in the Node event loop and they are called basically the same. That is, when I make a call using Node files and Internet I / O libraries, are those things that happen outside the stack whose callbacks are queued in the task queue?

+20
javascript javascript-events dom-events
source share
2 answers

... when I make a call using Node file and web I / O libraries, does this happen outside the stack whose callbacks are queued in the task queue?

Oh sure; they are asynchronous, like Ajax and setTimeout asynchronous. They perform some operation outside the call stack, and when they complete this operation, they add the event to the queue for processing in the event loop.

The Node API provides a kind of asynchronous ban, setImmediate . For this function, "some operation" that I mentioned above is "do nothing", after which the element is immediately added to the end of the event queue.

There is a more powerful process.nextTick that adds an event to the top of the event queue, effectively trimming lines and making all other events in the queue wait. When called recursively, it can cause a long delay for other events (until maxTickDepth ).

+15
source share

Both are completely different. The browser event loop is independent of I / O operations . But the Node js event loop is dependent on I / O. Here, the main purpose of the Node js event loop is to separate the main process and try to perform I / O and other timer APIs asynchronously.

And another difference is that we do not have the setImmediate () function in the browser. The difference between setTimeout () and setImmediate () is that the setTimeout () callback function will execute after the specified minimum threshold value in milliseconds. But in setImmediate () after performing any I / O operation, if a specific code is specified inside setImmediate (), it will be executed first.

Because usually

 setTimeout(() => { //some process }, 0); 

and

 setImmediate(() => { //some process }); 

are the same, and we cannot predict what will be done first. But in the future, Node js under the nodejs event loop mechanism, if both of them are present on any I / O callback , setImmediate () will be executed first. So,

 let fs = require('fs'); fs.readFile('/file/path', () => { setTimeout(() => { console.log('1'); }, 0); setImmediate(() => { console.log('2'); }); }); 

The output for the code above will be,

 2 1 
+1
source share

All Articles