Skip to content

Instantly share code, notes, and snippets.

@tonylukasavage
Created September 1, 2017 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonylukasavage/72517b09aa0a4d434dcb756c5ab33a1a to your computer and use it in GitHub Desktop.
Save tonylukasavage/72517b09aa0a4d434dcb756c5ab33a1a to your computer and use it in GitHub Desktop.
MyInterval with async_hooks
const async_hooks = require('async_hooks'),
fs = require('fs'),
http = require('http');
const hook = async_hooks.createHook({
init(asyncId, type, triggerAsyncId, resource) {
fs.writeSync(1, `[init] (${asyncId}:${triggerAsyncId}) ${type} - ${resource}\n`);
},
before(asyncId) {
fs.writeSync(1, `[before] (${asyncId})\n`);
},
after(asyncId) {
fs.writeSync(1, `[after] (${asyncId})\n`);
},
destroy(asyncId) {
fs.writeSync(1, `[destroy] (${asyncId})\n`);
}
}).enable();
class MyInterval extends async_hooks.AsyncResource {
constructor() {
super('MyInterval');
this.count = 0;
}
timeThing(callback) {
this.timer = setInterval(() => {
this.emitBefore();
callback(null, ++this.count);
this.emitAfter();
}, 500);
}
close() {
clearInterval(this.timer);
this.count = 0;
this.emitDestroy();
};
}
const int = new MyInterval();
int.timeThing((err, count) => {
if (count < 3) {
fs.writeSync(1, `count: ${count}\n`);
} else {
int.close();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment