JSFiddle - React, Tailwind, and code Playground

by Raynos

JavaScript

/*****************
 *
 * NOT TESTED
 *
 ****************/


/* Class: Buffer
 *  methods: append
 *
 *  Constructor: takes a function which will be the task handler to be called
 *
 *  .append appends a task to the buffer. Buffer will only call a task when the 
 *  previous task has finished
 */
var Buffer = function(handler) {
    var tasks = [];
    // empty resolved deferred object
    var deferred = $.when();

    // handle the next object
    function handleNextTask() {
        // if the current deferred task has resolved and there are more tasks
        if (deferred.isResolved() && tasks.length > 0) {
            // grab a task
            var task = tasks.shift();
            // set the deferred to be deferred returned from the handler
            deferred = handler(task);
            // if its not a deferred object then set it to be an empty deferred object
            if (!(deferred && deferred.promise)) {
                deferred = $.when();
            }
            // if we have tasks left then handle the next one when the current one 
            // is done.
            if (tasks.length > 0) {
                deferred.done(handleNextTask);
            }
        }
    }

    // appends a task.
    this.append = function(task) {
        // add to the array
        tasks.push(task);
        // handle the next task
        handleNextTask();
    };
};

// handler returns a deferred object.
var handler = function(task) {
    return $(task.obj).load(task.url, task.callback);
};

var Task = function(obj, url, callback) {
    this.obj = obj;
    this.url = url;
    this.callback = callback;
};

var buffer = new Buffer(handler);

for (var i = 0; i  < 10; i++ ) {
    (function (i) {
        var task = new Task(
            $("body"), 
            "", 
            function() { 
                console.log(i); 
            }
        );
        buffer.append(task);    
    }(i));
}