在 for 循环中设置间隔 Javascript

Setting Interval in for loop Javascript

我的代码一次给所有玩家发一张牌,然后间隔一段时间再发。我想给每个玩家发 3 张牌,每次发 1 张牌。

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);

}

你真的不需要间隔,你想要一个不断等待并发给下一个玩家的递归函数。

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);