Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript / Node.js event loop tick ids

I am wondering if there is some neat way of knowing if a function is called in the current tick (the tick in which the function was declared), or the next tick (or some future tick) of the Node.js event loop

for example:

function foo(cb){

  // we can fire callback synchronously
  cb();

  // or we can fire callback asynchronously
  process.nextTick(cb);

}

say will call foo like so:

function outer(){

   const currentTickId = process.currentTickId;

  function bar(){          //bar gets created everytime outer is called..

    if(process.currentTickId === currentTickId){
       //do something
    }
    else{

     // do something else
    }


  }

  // foo is always called in the same tick that bar was
  // declared, but bar might not be called until the next tick

  foo(bar);  


}

most applications won't need something like this, but I am writing a library and it would be useful to have this functionality, if it's possible! note that process.currentTickId is made up by me for this example

like image 272
Alexander Mills Avatar asked Oct 28 '25 19:10

Alexander Mills


1 Answers

It looks like you've already discovered process.nextTick.

You could use this to rig up a system to achieve "process.currentTickId" as the code in your question indicates you need:

process.currentTickId = 0;

const onTick = () => {
    process.currentTickId++;
    process.nextTick(onTick);
};

process.nextTick(onTick);
like image 132
Emmett Avatar answered Oct 31 '25 10:10

Emmett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!