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