有没有办法检测事件循环代码的运行转向?

时间:2015-06-10 03:55:53

标签: javascript node.js meteor

为了更好地理解异步和光纤,我想知道是否有一个全局变量在事件循环的每个回合中递增。

我希望能够在每个console.log语句中看到打印出的不同值,显然我们不能依赖系统时间来这样做。

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

1 个答案:

答案 0 :(得分:2)

setImmediate中的Node timers module可能会有效。 setImmediate文档中的引用:

  

安排"立即"在I / O事件之后执行回调   回调以及setTimeout和setInterval之前。返回一个   immediateObject可与clearImmediate()一起使用。你可以选择   也可以将参数传递给回调。

     

immediates的回调按照它们的顺序排队   创建。每个事件循环都处理整个回调队列   迭代。如果从执行内部排队立即   回调,立即赢得直到下一个事件循环才开始   迭代。

使用函数闭包和递归,您可以执行:

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

顺便说一句,在timers模块文档的开头,它声明:

  

所有定时器函数都是全局变量。你不需要()   这个模块是为了使用它们。

这就是setImmediate在不需要timers模块的情况下工作的原因。

我想我应该注意到我尝试使用process.nextTick做类似的事情,但是我收到一个错误,之后是一系列有用的警告消息,指出了上面的函数:

...
(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