我的代码一次向所有玩家发出一张牌,然后间隔一段时间才再次发牌。我想给每位玩家发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);

关于javascript - 在for循环Javascript中设置时间间隔,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40867458/

10-10 16:19