Are there significant differences between the Chrome browser event loop versus the node event loop?

前端 未结 3 821
梦谈多话
梦谈多话 2021-01-30 06:59

Philip Roberts does a brilliant job explaining the browser event loop here providing a clear explanation between the call stack, event loop, task queue, and then \"outside\" thr

3条回答
  •  长发绾君心
    2021-01-30 07:45

    Both are quite different. Browser's event loop doesn't depends on I/O Operations. But Node js event loop depends on I/O operations. Here the Node js event loop main goal is to separate out the main process and try to execute I/O operations and other timer API's asynchronously.

    And another difference is we don't have a function setImmediate() in Browser. Difference between setTimeout() and setImmediate() is In setTimeout() call back function will execute after the given minimum threshold value in milliseconds. But in setImmediate() once any I/O Operation is done, if particular code is given inside setImmediate(), it will be executed first.

    Because normally

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

    and

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

    are same and we can't predict which will execute first. But in Node js perspective under nodejs event loop mechanism if both are present under the callback of any I/O Operation, setImmediate() will get executed first. so,

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

    The output for above code will be,

    2
    1
    

提交回复
热议问题