Tuesday, January 18, 2011

waitFor function

Blind code (not tested)
any comments welcomed


function waitFor(condition, onSuccess, onTimeout, timeout, pollInterval) {
    // TODO: document + testcase
    pollInterval || (pollInterval = 100);
    var endTime = new Date().valueOf() + (timeout || 10000),
  errs, //condition eval errors
        c,    // condition eval result (can be object)  
        check = function () {
            try { c = condition(); }
            catch (ex) { (errs = (errs || [])).push(ex); }
            if (c)
                onSuccess(c);   //receives condition result (ca be {})
            else if (new Date().valueOf() < endTime)
                setTimeout(check, pollInterval);
            else if (onTimeout)
                onTimeout(errs); //receives err result (null or non empty [] of Error)
        };
    check();
};

No comments:

Post a Comment