JSFiddle - React, Tailwind, and code Playground

by rusci

HTML

<ul id='output'>

</ul>

JavaScript

// Function queue

// Buffer class. Has a public append method that expects some kind of Task.
// Constructor expects a handler which is a method that takes a ajax task
// and a callback. Buffer expects the handler to deal with the ajax and run
// the callback when it's finished
function Buffer(handler) {
    var queue = [];

    function run() {
        var callback = function () {
            queue.shift(); 
             // when the handler says it's finished (i.e. runs the callback)
             // We check for more tasks in the queue and if there are any we run again
             if (queue.length > 0) {
                  run();
             }
        }
        // give the first item in the queue & the callback to the handler
        handler(queue[0], callback);
    } 

    // push the task to the queue. If the queue was empty before the task was pushed
    // we run the task.
    this.append = function(task) {
        queue.push(task);
        if (queue.length === 1) {
            run();
        }
    }
}

// create a buffer object with a taskhandler
// that loads the task.url into the task.item and calls the callback 
// when its finished
var buffer = new Buffer(function(task, callback) {
    task(function() {
        // call an option callback from the task
        if (task.callback) task.callback();
        // call the buffer callback.
        console.log('Task done');
        callback();
    });
});

var tasks = [
    function(callback) {
        setTimeout(function() {
            $('output').insert({
                bottom: '<li>Uno - ' + new Date() + '</li>'
            });
            callback();
        }, 4000)
    },
    function(callback) {
        setTimeout(function() {
            $('output').insert({
                bottom: '<li>Due - ' + new Date() + '</li>'
            });
            callback();
        }, 2000)
    }
];

$('output').insert({
                bottom: '<li>Start - ' + new Date() + '</li>'
            });

for (i = 0; i <...