Dayo Dayo - 8 days ago 6
Javascript Question

Setting Interval in for loop Javascript

My code deals a card to all players at once, then there is an interval before dealing again. I want to deal 3 cards to each player, 1 card at a time with interval.

function dealPlayers() {

var counter = 1;

var timer = setInterval(function () {

for (var i = 0; i < gameDB.plySeatArray.length; i++) {

gameDB.plySeatArray[i].addCard(getNextCard(), false);

};

if (counter >= 3) {
clearInterval(timer);
}

counter++;

}, 1000);

}

Answer

You dont really want intervals, you want a recursive function that constantly waits and deals to the next player.

function dealCard(playerIndex) {
    gameDB.plySeatArray[playerIndex].addCard(getNextCard(), false);
    if ((playerIndex + 1) == gameDB.plySeatArray.length) {
        //end of the queue, reset to the first player
        playerIndex = 0;
    } else {
        playerIndex++;
    }

    //Check the next playerIndex's card
    if (/*playerIndex doesnt have 3 cards, deal him in in a second*/) {
        setTimeout(function() {
            dealCard(playerIndex);
        }, 1000);
    }
}

dealCard(0);