forEachInTime

by Konstantin Cryman

JavaScript

const forEachInTime = function( arr, callback, delay ){
    return new Promise( ( resolveOnEnd, reject ) => {
        let nextIteration = 0;
        let goNextIteration;
        goNextIteration = function(){
            callback( arr[ nextIteration ], nextIteration );
            if( nextIteration + 1 < arr.length ){
                setTimeout( () => {
                    nextIteration += 1;
                    goNextIteration();
                }, delay );
            } else {
                resolveOnEnd( {
                    arr,
                    delay
                } );
            }
        };
        goNextIteration();
    } );
};