23

Below is the code present in "practise01.js" file,

function fn(name){
   return f;

   function f(){
       var n = name;
       console.log("Next TICK "+n+", ");        
   }
}

function myTimeout(time,msg){
   setTimeout(function(){
       console.log("TIMEOUT "+msg);
   },time); 
}

process.nextTick(fn("ONE"));
myTimeout(500,"AFTER-ONE");
process.nextTick(fn("TWO"));
myTimeout(500,"AFTER-TWO");
process.nextTick(fn("THREE"));
myTimeout(500,"AFTER-THREE");
process.nextTick(fn("FOUR"));

The output from running above code is

rahul@rahul:~/myPractise/PlainNodeJSPractise01/Process$ node practise01.js                  

Next TICK ONE, 
Next TICK TWO, 
Next TICK THREE, 
Next TICK FOUR, 
TIMEOUT AFTER-ONE
TIMEOUT AFTER-TWO
TIMEOUT AFTER-THREE

Now I wrote the code without using process.nextTick, in "practise02.js", as follows,

function myTimeout(time,msg){
  setTimeout(function(){
        console.log("TIMEOUT "+msg);
  },time);  
}

function fn(name){
  return f;

  function f(){
    var n = name;
    console.log("Next TICK "+n+", ");       
  }
}

fn("ONE")();
myTimeout(500,"AFTER-ONE");
fn("TWO")();
myTimeout(500,"AFTER-TWO");
fn("THREE")();
myTimeout(500,"AFTER-THREE");
fn("FOUR")();

after running the above code the output is

rahul@rahul:~/myPractise/PlainNodeJSPractise01/Process$ node practise02.js 
Next TICK ONE, 
Next TICK TWO, 
Next TICK THREE, 
Next TICK FOUR, 
TIMEOUT AFTER-ONE
TIMEOUT AFTER-TWO
TIMEOUT AFTER-THREE

If you see both the outputs are same.

So in which case I need to go with process.nextTick ?

When I tried to read more, what I came to understand is If I need to execute some function immediately when the eventloop is empty than go for "process.nextTick".

So how does its different from my second approach.

Please explain me or give me some pointers

2
  • You are not seeing the difference because you use either only console.log or only process.nextTick. Do console log, next tick, console.log and you'll see the difference.
    – Azamantes
    Commented Nov 16, 2016 at 10:25
  • I didn't understood. Can you please elaborate Commented Nov 16, 2016 at 10:38

3 Answers 3

12

The node documentation is actually pretty good in explaining when and why using nextTick:

https://nodejs.org/api/process.html#process_process_nexttick_callback_args

What it does:

This is not a simple alias to setTimeout(fn, 0), it's much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop.

and when to use:

This is important when developing APIs in order to give users the opportunity to assign event handlers after an object has been constructed but before any I/O has occurred...

function definitelyAsync(arg, cb) {
  if (arg) {
    process.nextTick(cb);
    return;
  }

  fs.stat('file', cb);
}
definitelyAsync(true, () => {
  foo();
});
bar(); // will now allways be called before foo()
1
  • "and when to use:" this is in no way an exhaustive representation of when to use process.nextTick, so suggesting so is misleading. Commented Jun 27, 2023 at 21:42
8

First lets understand the behaviour of process.nextTick()

Eventloop has phases where in each phase different type of async functions get executed.

process.nextTick(callback[, ...args]) is a part of the asynchronous API of nodeJS. But it is not technically part of the event loop.

nextTickQueue will be processed after the current operation is completed, regardless of the current phase of the event loop.

any time we call process.nextTick() in a given phase of eventloop, callback passed to process.nextTick() will be resolved before the event loop continues.

Why we need to use process.nextTick

It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example:

// WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
function maybeSync(arg, cb) {
  if (arg) {
    cb();
    return;
  }

  fs.stat('file', cb);
}
const maybeTrue = Math.random() > 0.5;

maybeSync(maybeTrue, () => {
  foo();
});

bar();

It is not clear whether foo() or bar() will be called first. The following approach is much better:

function definitelyAsync(arg, cb) {
  if (arg) {
    process.nextTick(cb);
    return;
  }

  fs.stat('file', cb);
}

already @Johannes Merz has mentioned in his answer why it's good to use process.nextTick(callback) rather than setTimeout(callback, 0)

For more refer here

5
  • How is definitelyAsync always going to be asynchronous? Why is nextTick considered asynchronous?
    – Melab
    Commented Feb 11, 2022 at 17:56
  • "It's the way we can tell the JS engine to process a function asynchronously (after the current function), but as soon as possible, not queue it." --------------REFER HERE===> nodejs.dev/learn/understanding-process-nexttick Commented Feb 16, 2022 at 7:49
  • what is wrong if the API is not either 100% synchronous or 100% asynchronous. Commented Mar 24, 2023 at 16:16
  • @Sheldeeb If you don't know whether a function is synchronous or asynchronous How will you get the result of the function? For synchronous you don't need async await or promise. For Async, you need async await or promise. A function async or sync determines how to write code further. Commented Mar 30, 2023 at 8:02
  • simply, if you passed a cb you expect it is a sync function, otherwise it runs synchoronusly Commented Apr 1, 2023 at 19:42
3

You have your answer in your post where you share your output with us in:

rahul@rahul:~/myPractise/PlainNodeJSPractise01/Process$ node practise02.js 
Next TICK ONE, 
Next TICK TWO, 
Next TICK THREE, 
Next TICK FOUR, 
TIMEOUT AFTER-ONE
TIMEOUT AFTER-TWO
TIMEOUT AFTER-THRE

If we change your timeout interval from 500 to 0 still same result:

function fn(name){
   return f;

   function f(){
       var n = name;
       console.log("Next TICK "+n+", ");
   }
}

function myTimeout(time,msg){
   setTimeout(function(){
       console.log("TIMEOUT "+msg);
   },time);
}

process.nextTick(fn("ONE"));
myTimeout(0,"AFTER-ONE");// set timeout to execute in 0 seconds for all
process.nextTick(fn("TWO"));
myTimeout(0,"AFTER-TWO");
process.nextTick(fn("THREE"));
myTimeout(0,"AFTER-THREE");
process.nextTick(fn("FOUR"));

Results

Next TICK ONE, 
Next TICK TWO, 
Next TICK THREE, 
Next TICK FOUR, 
TIMEOUT AFTER-ONE
TIMEOUT AFTER-TWO
TIMEOUT AFTER-THREE

when you use process.nextTick you basically ensure that the function that you pass as a parameter will be called immediately in the next tick ie. start of next event loop.So that's why all your function in next tick executes before your timer ie. setTimeout next tick doesn't mean next second it means next loop of the nodejs eventloop. Also next tick ensures that the function you are trying to call is executed asynchronously. And next tick has higher priority than your timers, I/O operations etc queued in the eventloop for execution. You should use nextTick when you want to ensure that your code is executed in next event loop instead of after a specified time. nextTick is more efficient than timers and when you want to ensure the function you call is executed asynchronously . You can find more information on this in nodejs docs

6
  • It is my 5th article trying to learn about next tick, saying will be called immediately in the next tick ie. start of next event loop. But nowhere I did I see a loop. Can you kindly specify where is the so called "event loop" ? Commented Feb 14, 2018 at 7:00
  • 4
    I think "[...]will be called immediately in the next tick ie. start of next event loop[...]" (and others) is a bit missleading. The event loop consists of several phases, process.nextTick will not start with the start of the next loop but rather right after the current operation
    – seasick
    Commented Jun 1, 2018 at 14:32
  • process.nextTick() fires immediately on the same phase. Not with next event loop. @seasick mentions right here. Commented Aug 15, 2018 at 6:26
  • any time you call process.nextTick() in a given phase, all callbacks passed to process.nextTick() will be resolved before the event loop continues. Commented Aug 15, 2018 at 6:32
  • @seasick Thanks for pointing it out, removed misleading reference, Do update the answer in case you feel there are any other inconsistencies
    – AJS
    Commented Aug 20, 2018 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.