views:

72

answers:

2

I am learning node.js and most of examples I can find are dealing with simple examples. I am more interested in building real-world complicated systems and estimating how well event based model of node.js can handle all the use cases of a real application.

One of the common patterns that I want to apply is let blocking execution to time-out if it does not occur within certain timeout time. For example if it takes more than 30 seconds to execute a database query, it might be too much for certain application. Or if it takes more than 10 seconds to read a file.

For me the ideal program flow with timeouts would be similar to the program flow with exceptions. If an event does not occur within certain predefined timeout limit, then the event listener would be cleared from the event loop and a timeout event would be generated instead. This timeout event would have an alternate listener. If the event is handled normally, then both the timeout listener and event listener are cleared from the event loop.

Is there a general mechanism for timeout handling and cleaning up timed out processes? I know some types such as socket have timeout parameter but it is not a general mechanism that applies to all events.

+1  A: 

There is nothing like this at the moment (that i know of, but i don't know everything).

The only thing i can think of is that you reset it yourself somehow. I've given an example below but I think it may have some scope issues. Should be solvable though.

var to
function cb() {
    clearTimeout(to)
    // do stuff
}
function cbcb() {
    cb()
}
function cancel() {
    cb = function() {} // notice empty
}
fs.doSomethingAsync(file, cbcb)
to = setTimeout(cancel, 10000)
Tor Valamo
A: 
Function.prototype.timeout = function(ms, callback){
    var fn = this, tick = setTimeout(function(){
        ms = 0;
        callback();
    }, ms);
    return function(){
        clearTimeout(tick);
        ms && fn.apply(null, arguments);
    }
};

function on_ok(){
    alert('ok')
};
function on_timeout(){
    alert('timeout')
};
setTimeout( on_ok.timeout(50, on_timeout), 100)
Lauri