Conditional wait

wrapper around any function using setTimeout!

by donabrams

HTML

<div id="content"> </div>
<div id="condStatus"> </div>


<div id="testscope"> </div>

JavaScript

$(function() {
    var _cond_wait_worker = function (attempts, max_attempts, delay, flagFunc, flagScope, func, scope, args) {
        if (attempts >= max_attempts) {
            return false;
        }    
        if (!flagFunc.apply(flagScope)) {
            //increment attempts
            var args2 = [attempts + 1].concat(Array.prototype.slice.call( arguments, 1));
            setTimeout(_cond_wait_worker_unroller, delay, args2);
        }
        else {
            //apply just the arguments!
            func.apply(scope, args);
        }
    };
    var _cond_wait_worker_unroller = function(array) {
        _cond_wait_worker.apply(this, array);
    }
        
    //var _cond_wait = function (max_attempts, delay, flagFunc, func, /*, arguments */) {
    var _cond_wait = function (max_attempts, delay, flagFunc, flagScope, func, scope /*, arguments */) {
        if (typeof flagScope == 'function') {
            $('#testscope').html("using this as scope");
            //does not work yet!
            _cond_wait_worker(0, max_attempts, delay, flagFunc, this, flagScope, this, 
                          Array.prototype.slice.call( arguments, 6 ));
        }
        else {
            $('#testscope').html("scopes provided");
            _cond_wait_worker(0, max_attempts, delay, flagFunc, flagScope, func, scope, 
                          Array.prototype.slice.call( arguments, 6 ));
        }
    };
    var something = {
        counter: 0,
        isCompleted: function() {
            this.counter = this.counter + 1;
            $('#content').html("try " + this.counter);
            return this.counter > 6;
        },
        gitErDone: function(someHtml, note) { 
            $('#content').html("Completed after " + this.counter + ":" + someHtml);
            $('#condStatus').html(note);
        },
        gitErStarted: function(someHtml, note) {
            // longer syntax
            //_cond_wait(20, 1000, something.isCompleted, something, something.gitErDone,...