javascript - for循环可以等到其中的函数执行完毕吗?

标签 javascript jquery function for-loop

我正在构建一个 Simon 游戏,并且为每个新回合构建了一个函数:

var game = [];
var squares = ["green", "red", "blue", "yellow"];

var newRound = function() {
  // adds a new round to the end of the game array
  game.push(squares[Math.floor(Math.random() * squares.length)]);

  // for loop to run through the game array
  for (var x = 0; x < game.length; x++) {
    playButton(game[x]);
  }
}

然后,我构建了另一个函数来控制每次方 block 被用户击中或在我的 for 循环中循环时的动画和声音

var playButton = function(color){
  $("#"+color).addClass(color+"--active active", 300, function(){
     $("#audio-"+color).trigger('play');
     $("#"+color).removeClass(color+"--active active", 300)
});

现在,我的 for 循环只是一次循环遍历所有动画和声音。如何让 for 循环等待 playButton 函数完成执行后再循环?

code sample on CodePen

最佳答案

您可以将 for 循环转换为一个递归函数,该函数播放当前按钮,然后在所有动画完成后尝试播放下一个按钮。像这样的东西:

var newRound = function() {
  // adds a new round to the end of the game array
  game.push(squares[Math.floor(Math.random() * squares.length)]);

  // start playing from the first button
  playButton(game, 0);
}

function playButton(game, index) {
  if (index < game.length) { // if this button exists, play it
    var color = game[index];
    $("#" + color).addClass(color + "--active active", 300, function() {
      $("#audio-" + color).trigger('play');
      $("#" + color).removeClass(color + "--active active", 300, function() {
        playButton(game, index + 1); // once this button was played, try to play the next button
      });
    });
  }
}

关于javascript - for循环可以等到其中的函数执行完毕吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33551873/

相关文章:

php - 如何处理服务器和客户端之间的时区?

javascript - 如何根据 jQuery 中 bootstrap 下拉列表的选择显示和隐藏 div 元素

javascript - 如何减去两个相关选择html的选项

php - 如何在 jQuery 的页面之间保留从 PHP 登录检索到的数据

javascript - 尝试拉取 xml/json

javascript - 单击功能 "this"不起作用

Jquery 自动完成动态文本框问题

javascript - 将一个函数作为另一个函数的参数

python - 如何将数据从一个类传递给另一个函数(在 HTMLParser 中)?

java - 如何在java中实现杰卡德系数?