Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and when to use process.nextTick?

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

like image 530
Rahul Shivsharan Avatar asked Nov 16 '16 10:11

Rahul Shivsharan


People also ask

What is the difference between setImmediate and process nextTick?

1. process. nextTick() is used to schedule a callback function to be invoked in the next iteration of the Event Loop. setImmediate() method is used to execute a function right after the current event loop finishes.

Why do I need setImmediate?

setImmediate() This method is used to break up long running operations and run a callback function immediately after the browser has completed other operations such as events and display updates.

What is nextTick?

The nextTick() function allows you to execute code after you have changed some data and Vue has updated the page to reflect your changes. Pass a callback to nextTick() and Vue will execute the callback immediately after updating the DOM.

Why do we want sometimes to use setImmediate instead of using setTimeout?

The main advantage to using setImmediate() over setTimeout() is setImmediate() will always be executed before any timers if scheduled within an I/O cycle, independently of how many timers are present.

How does nexttick() work in JavaScript?

When we pass a function to process.nextTick (), we instruct the engine to invoke this function at the end of the current operation, before the next event loop tick starts: The event loop is busy processing the current function code. When this operation ends, the JS engine runs all the functions passed to nextTick calls during that operation.

Is nexttick() a synchronous or asynchronous method?

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. It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example: // WARNING! DO NOT USE!

When should I use nexttick instead of timer?

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

Why am I not seeing the difference between console log and nexttick?

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. I didn't understood. Can you please elaborate The node documentation is actually pretty good in explaining when and why using nextTick:


1 Answers

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()
like image 103
Johannes Merz Avatar answered Oct 01 '22 12:10

Johannes Merz