Skip to content

Instantly share code, notes, and snippets.

@formula1
Created November 11, 2014 22:14
Show Gist options
  • Save formula1/3ba79ba5bcbecc16f681 to your computer and use it in GitHub Desktop.
Save formula1/3ba79ba5bcbecc16f681 to your computer and use it in GitHub Desktop.
var ee = require('events').EventEmitter;
function some_cuteness(next){
var our_event = new ee();
var functioned = 0;
cb("we're in the main");
for(var counter=1;counter<4;counter++)
cb("counting = "+counter);
var ending = process.hrtime()[0]+2;
while(process.hrtime()[0] < ending)
if(process.hrtime()[1]%333333333 <15000)cb("wait for it (never do this...)");
our_function();
cb("Back in the Main");
our_event.once("the event!", function(){
cb("This event will happen once");
});
our_event.on("the event!", removable);
our_event.on("the event!", function(){
cb("This will event will stick around");
});
var timeoutstart = Date.now();
setTimeout(function(){
var timeoutend = Date.now();
cb("this happened in \"1\" millisecond (not really)");
cb("started: "+timeoutstart);
cb("ended: "+timeoutend);
cb("difference: "+(timeoutend - timeoutstart));
our_event.emit("the event!");
cb("Still in Timeout");
},1)
process.nextTick(function(){
cb("this happened the next Tick");
our_event.emit("the event!");
cb("Still in the Process");
});
setImmediate(function(){
cb("this happened \'immediately\' (not really)");
our_event.emit("the event!");
cb("Still in the Process");
})
cb("still in the main");
function our_function(){
cb("we're in the function.");
}
function removable(){
functioned++;
cb("this event will be removed when. functioned:"+functioned+" == 3");
if(functioned == 3)
our_event.removeListener("the event!",removable)
}
function cb(msg){
console.log(msg);
if(typeof next != "undefined")
next(msg);
}
our_event.emit("the event!");
ending = process.hrtime()[0]+2;
while(process.hrtime()[0] < ending)
if(process.hrtime()[1]%333333333 <15000)cb("wait for it (again never do this...)");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment