lfk*_*wtz 1 javascript jquery for-loop function
我正在构建一个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]);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我构建了另一个函数,它控制动画和声音每次广场被用户击中,或循环通过我的for循环
var playButton = function(color){
$("#"+color).addClass(color+"--active active", 300, function(){
$("#audio-"+color).trigger('play');
$("#"+color).removeClass(color+"--active active", 300)
});
Run Code Online (Sandbox Code Playgroud)
现在,我的for-loop只需一次循环播放所有动画和声音.如何让for循环等待playButton函数在再次循环之前完成执行?
您可以将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
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1711 次 |
| 最近记录: |