JavaScript / Node.js事件循环滴答ID
我想知道是否有一些干净的方式知道是否在当前的时间内调用一个函数(函数被声明的时间间隔),或者是Node.js事件循环的下一个时间戳
例如:
function foo(cb){ // we can fire callback synchronously cb(); // or we can fire callback asynchronously process.nextTick(cb); }
说会像这样称呼foo:
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(bar); //foo is always called in the same tick that bar was declared, but bar might not be called until the next tick }
大多数应用程序不需要这样的东西,但是我正在编写一个库,如果可能的话,这个function是有用的! 注意process.currentTickId
是由我为这个例子组成的
看起来你已经发现了process.nextTick
。
你可以用这个来build立一个系统来实现“ process.currentTickId
”,因为你的问题中的代码表明你需要:
process.currentTickId = 0; const onTick = () => { process.currentTickId++; process.nextTick(onTick); }; process.nextTick(onTick);