1

I have alrady watched this wonderfully video related to the event loop work https://www.youtube.com/watch?v=8aGhZQkoFbQ

From some reading,I suppose process.nextTick will put the callback at the very beginning of the event queue .Also I see some people use nextTick to execute a function immediately

I try to write some code to confirm it

function printNextTick(s){
    process.nextTick(function(){
        console.log(s)
    })
}
for (var i=0;i<5;i++){
    printNextTick(i)
} 

what I expect is 4,3,2,1,0,because nextTick will always put the callback at the beginning of the queue,and the script is "execute to complete", which means no callback will be execute during "put callback to the queue","4" is push last,so after the script complete,"4" should at the first place of the queue,that is why I expect "4" comes out first

But it is not correct

================================ Update ==================================== Here the new code

function printNextTick(s){
    process.nextTick(function(){
        console.log("nextTick : "+s)
    })
}
function printTimeout(s){
    setTimeout(function(){
        console.log("timeout : "+s)
    },0)
}
for (var i=0;i<5;i++){
    printTimeout(i)
}
for (var i=0;i<5;i++){
    printNextTick(i)
}
//nextTick : 0
//nextTick : 1
//nextTick : 2
//nextTick : 3
//nextTick : 4
//timeout : 0
//timeout : 1
//timeout : 2
//timeout : 3
//timeout : 4

Just wonder why some people treat nextTick as immediate Originally,I suppose nextTick will put callback at the beginning of the event queue rather than ending as normal,for now,I suppose the queue for nextTick has a higher priority than other queues ,at least higher than queue for timeout

================== Update ===============

Not true above ! The result for code below is quite unpredictable

function printNextTick(s){
    process.nextTick(function(){
        console.log("nextTick : "+s)
    })
}

function printTimeout(s){
    setTimeout(function(){
        console.log("timeout : "+s)
        for (var i=0;i<5;i++){
            printNextTick(i)
        }

    },0)
}
for (var i=0;i<5;i++){
    printTimeout(i)
}
Guichi
  • 2,150
  • 1
  • 19
  • 27
  • *Just wonder why some people treat `nextTick` as immediate* Whose are these people? It is not "immediate", it is "next". –  Sep 09 '16 at 04:19
  • Possible duplicate of [nextTick vs setImmediate, visual explanation](http://stackoverflow.com/questions/17502948/nexttick-vs-setimmediate-visual-explanation) –  Sep 09 '16 at 04:20
  • @torazaburo the answer you referred is wrong ,I updated it – Guichi Sep 09 '16 at 10:38

3 Answers3

1

Any callbacks you pass to process.nextTick() are appended to an internal queue that gets flushed (to a maximum IIRC so as not to completely starve the rest of the event loop), in order, at the "next tick." So in your example you are first appending a callback that prints '0', then a callback that prints '1', etc. These are then executed in order and you see the numbers printed in numerical order.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Why many people treat `nextTick` as equivalent to `immediate` ?Originally, I suppose the reason is that 'nextTick' put callback at beginning of the queue (rather than end as normal). For now,I suppose nodejs maintain multiple 'event queue' and the one for `nextTick` has higher priority – Guichi Sep 09 '16 at 03:38
  • 1
    They probably treat them similarly because they more or less have the same desired effect (allowing the call stack to unwind and to give users a chance to attach event handlers before emitting an event right away for example). Nowadays though (IIRC) `process.nextTick()` callbacks get fired on the *same tick* but *before* I/O callbacks occur. `setImmediate()` callbacks on the other hand do actually get called at the beginning of the *next tick*. It's a bit confusing but the behavior has changed over time (and `setImmediate()` came much later in node's life). – mscdex Sep 09 '16 at 05:07
1

Just wonder why some people treat nextTick as immediate

From the documentation:

process.nextTick() fires immediately on the same phase setImmediate() fires on the following iteration or 'tick' of the event loop In essence, the names should be swapped. process.nextTick() fires more immediately than setImmediate() but this is an artifact of the past which is unlikely to change. Making this switch would break a large percentage of the packages on npm. Every day more new modules are being added, which mean every day we wait, more potential breakages occur.

Originally,I suppose nextTick will put callback at the beginning of the event queue rather than ending as normal,for now,I suppose the queue for nextTick has a higher priority than other queues, at least higher than queue for timeout

From process docs:

process.nextTick() runs before any additional I/O events (including timers)

Boolean_Type
  • 1,146
  • 3
  • 13
  • 40
0

To understand the difference between nextTick and setTimeout, consider my implementation of setTimeout:

function setTimeout2(callback, ms) {
    var t = process.hrtime(), 
    _next = () => 
        process.nextTick(process.hrtime(t)[0] > !!ms?callback:_next);
    _next();
}

function printNextTick(s){
    process.nextTick(() => console.log('n'+s))
}

function printTimeout(s){
    setTimeout2(() => {
        console.log('t'+s);
        for (var i=0;i<5;i++)
            printNextTick(s+':'+i);
    });
}

for (var i=0;i<5;i++)
    printTimeout(i);

It behaves very similar to setTimeout, except it is less efficient. To answer your question, no, process.nextTick(callback) appends callback to the nextTick queue. setTimeout(callback, ms) also appends its callback to the nextTick queue if diff > ms (not >= ms).

Hin Fan Chan
  • 1,543
  • 10
  • 11