Delay tick() of each sprite within a globalTick() JS

https://stackoverflow.com/questions/42322662/delay-tick-of-each-sprite-within-a-globaltick-js

by dpren

HTML

<button>spawnArrows</button>

JavaScript

let notes = ["A", "B", "C", "D", "E"];
let spriteList = [];
let spawnQueue = [];
let delayTime = 500;

function globalTick() {
    spriteList.forEach(sprite => sprite.tick());
    requestAnimationFrame(globalTick);
}
globalTick();

$('button').click(onButtonClick);

function onButtonClick() {
    const kickOffQueue = spawnQueue.length <= 0;

    notes.forEach(note =>
        spawnQueue.push(() => spawnArrow(note))
    );

    if (kickOffQueue) {
        // here you can set delay time of the first execution
        consumeSpawnQueue(500);
    }
}

function consumeSpawnQueue(nextDelayTime) {
    if (spawnQueue.length > 0) {
        setTimeout(() => {
            spawnQueue.shift()();
            consumeSpawnQueue(delayTime);
        }, nextDelayTime);
    }
}

function spawnArrow(note) {
    var dirCode = Math.floor((Math.random() * 8));
    spriteList.push(new Arrow(dirCode, note));
}

class Arrow {
    constructor(dirCode, note) {
        this.dirCode = dirCode;
        this.x = 0;
        this.domEl = $(`<div>${note}${dirCode}</div>`).appendTo('body');
    }

    tick() {
        this.x += 1;
        this.domEl.css({
            marginLeft: this.x
        });
    }
}