JSFiddle - React, Tailwind, and code Playground

by Oski Krawczyk

JavaScript

/* 
  Array.each_asynchronously  
  
    Description:
  Works just like Array.each except runs each iteration on a specified delay. 
  This means that script execution will continue in between each iteration, 
  rather than halting until the full array has been processed. 
  
  Arguments:
    -    fn: (function) The function to execute on each item in the array. It is
        passed three arguments: the item, the index and the array itself.
    -    delay: (number, optional) Duration of timer for each call to fn. Defaults 
        to 10ms. 
    -    bind: (object, optional) The object to be used as 'this' in the fn.
    
    Example:
    ['brawndo','has','electrolytes'].each_asynchronously(function(str,i,arr){ 
        console.log(str); 
    }, 1000);
*/

Array.implement({
    each_asynchronously: function(fn, delay, bind) {
        if (this.length == 0) return this;
        var delay = delay || 10;
        var items = this.concat();
        var index = 0;

        (function() {
            fn.run([items.shift(), index, this], bind);
            index += 1;
            if (items.length > 0) setTimeout(arguments.callee.bind(this), delay);
        }).delay(delay, this);

        return this;
    }
});

['brawndo', 'has', 'electrolytes'].each_asynchronously(function(str, i, arr) {
    console.log(str);
}, 1000);