Timeout Event Emitter

1,107 views
Skip to first unread message

manimal45

unread,
May 18, 2011, 3:50:41 AM5/18/11
to nodejs
Does anyone knows of a module that extend EventEmitter to add a
timeout to it.
Its API would be the same as EventEmitter's one , except that
#.once would have an optional timeout argument defining a timeout
setting.
Such a feature can simplify and encourage clean error handling.

Here' an example of what is usage can look like :
var E = new TimeoutEventEmitter ();
function listener(err, data){
sys.puts(err);
}

E.once("event1", listener, 500); // If event is not triggered within
1000 ms, listener will be called with a TimeoutError
setTimeout(function(){
E.emit("event1");
}, 1000);


// This should output a TimeoutError after 500 ms.

Note :
Paddle module (https://github.com/andyet/paddle) tries to achieve the
same goal.
Paddle triggers a timeout callback if an async method does not calls a
callback before a given timeout (Paddle does not apply to
EventEmitters).
IMO, the small feature Paddle misses is that when timeout callback is
called, nothing prevents the initial callback to be called after
timeout. This can lead to inconsistent situations. Example :
- A timeout is applied to an async connection-like method
- After timeout second, connection is not ready, so timeouterror
callback is called by paddle
- After timeout + x second, connection finally gets ready, so standard
callback is called

That's why I'm looking for another approach.

manimal45

unread,
May 18, 2011, 4:11:18 AM5/18/11
to nodejs
Sorry,

I was wrong about Paddle.
Paddle actually does prevent two callbacks from being called.
To be honest, it even does a lot more.

Nevertheless, I still think TimeoutOutEE might be useful.

Laurie Harper

unread,
May 18, 2011, 8:31:19 AM5/18/11
to nod...@googlegroups.com
You can set this up easily yourself when you need it:

function waitFor(emitter, event, timeout, fn) {
var called = false, handler, timer;

handler = function() {
called = true;
clearTimeout(timer);
fn.apply(this, arguments);
}

var timer = setTimeout(function() {
emitter.removeListener(handler);
if (! called) return fn("TIMEOUT");
}, timeout);

emitter.once(event, handler);
}

L.

> --
> You received this message because you are subscribed to the Google Groups "nodejs" group.
> To post to this group, send email to nod...@googlegroups.com.
> To unsubscribe from this group, send email to nodejs+un...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/nodejs?hl=en.
>

--
Laurie Harper
http://laurie.holoweb.net/

Laurie Harper

unread,
May 18, 2011, 8:51:11 AM5/18/11
to nod...@googlegroups.com
Oops -- you don't need the 'called' flag, just the timer handle and callback wrapper.
Reply all
Reply to author
Forward
0 new messages