nextTick vs setImmediate, visual explanation

后端 未结 5 1709
一整个雨季
一整个雨季 2020-12-04 05:02

I\'m very confused about the differences between nextTick and setImmediate. I\'ve read all the documentation about them on the internet but I still don\'t understand how the

5条回答
  •  星月不相逢
    2020-12-04 05:54

    Below gives you better clarity.

    setImmediate

    1. It's execute a script once the current poll phase completes.
    2. It's a timer module function and timer functions are global, you can call them without require.
    3. It can cleared by clearImmediate().
    4. Set "immediate" execution of the callback after I/O events' callbacks before setTimeout() and setInterval().

    nextTick

    1. It's a process global object function of NodeJS.
    2. All callbacks passed to process.nextTick() will be resolved before the event loop continues.
    3. Allow users to handle errors.
    4. Helps to try the request again before the event loop continues.

    Simple code Snippet.

    console.log("I'm First");
    
    setImmediate(function () {
      console.log('Im setImmediate');
    });
    
    console.log("I'm Second");
    
    process.nextTick(function () {
      console.log('Im nextTick');
    });
    
    console.log("I'm Last");
    
    /*
    Output
    $ node server.js
    I'm First
    I'm Second
    I'm Last
    Im nextTick
    Im setImmediate
    */
    

提交回复
热议问题