Scheduler

by mmarcon

HTML

<section class="messages">
    
</section>

JavaScript

(function() {
    var messages = $('.messages'),
        log = function(m) {
            messages.append('<p>' + m + '</p>')
        };
    var ready = false,
        methods = {
            a: function() {
                setTimeout(function() {
                    log('a');
                    ready = true;
                }, 3000);
            },
            b: function() {
                log('b')
            },
            c: function() {
                log('c')
            }
        },
        queue = [],
        t,
        call = function(context, args, f, async){
            if (ready || async) {
                f.apply(context, args);
            }
            else {
                queue.push(f.bind(context, args));
                if (!t) {
                    t = setInterval(function(){
                        if (queue.length === 0) {
                            clearInterval(t);
                            return;
                        }
                        if (!ready) return;
                        queue.shift()();
                    }, 100);
                }
            }
        };

    call(this, [], methods.a, true);
    call(this, [], methods.b);
    call(this, [], methods.c);
}());