Guichi
Guichi

Reputation: 2343

is process.nextTick() execute immediately

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)
}

Upvotes: 1

Views: 811

Answers (3)

Boolean_Type
Boolean_Type

Reputation: 1274

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)

Upvotes: 1

Hin Fan Chan
Hin Fan Chan

Reputation: 1643

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).

Upvotes: 0

mscdex
mscdex

Reputation: 106696

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.

Upvotes: 1

Related Questions