Is there a way to determine which of the loop codes the loop is running?

To get a better understanding of async and Fibers, I am wondering if there is a global variable that is incremented for each revolution of the event loop.

I would like to see various values ​​printed in each of these console.log statements, and obviously we cannot rely on the system time to do this.

function getEventLoopCounter () { /* magic occurs */ }

// Turn 1 
console.log("I'm on loop number: ", getEventLoopCounter());

// Turn > 1 
setTimeout(function(){
  console.log("I'm on different loop: ", getEventLoopCounter());
}, 0);

      

+3


source to share


1 answer


Perhaps setImmediate

from Node the timer module will work. Quoting from the documentation for setImmediate

:

To schedule callbacks to "immediately" execute after I / O events, and before setTimeout and setInterval. Returns an instantObject for possible use with clearImmediate (). Optionally, you can also pass arguments to the callback.

Callbacks for direct clients are queued in the order in which they were created. The entire callback queue is processed each event loop iteration. If you enqueue from within the executable a callback that doesn't fire immediately until the next iteration event loop.

Using function closure and recursion, you can:

var eventLoopCounter = 0;
setImmediate(function incrementEventLoopCounter() {
  eventLoopCounter++;
  setImmediate(incrementEventLoopCounter);
});
// Logging the total number of iterations every second.
setInterval(function() {
  console.log('The event loop has finished '
               + eventLoopCounter
               + ' iterations.');
}, 1000);

      

By the way, at the beginning of the module documentation it timers

says:



All timer functions are global. You don't need to require () this module to use them.

And that's why it setImmediate

works without requiring a module timers

.

I guess I should point out that I was trying to do something like this using process.nextTick

but I got an error preceding a series of helpful warning messages that pointed me to the above function:

...
(node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
(node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.

RangeError: Maximum call stack size exceeded

      

+1


source







All Articles