这是一个 jquery/javascript 问题。 所以我有一个包含按钮编号的数组,并将这些按钮输出到一个按钮上,这将导致该按钮被单击。问题是,如果我运行循环,所有按钮都会立即被单击。相反,我希望它延迟输出数字,以便在 1 秒延迟后按下按钮。
以下是 Simon 游戏项目的链接: https://codepen.io/roger1891/full/vmYqwx/
点击第一个按钮后问题就显现出来了。之后,计算机将同时按下接下来的 2 个按钮,而不是在延迟 1 秒后分别按下它们。
问题出在 myloop() 函数中的循环中:
sequenceArray.forEach(function(item, index, array){
//click button by getting the last index of the array
//$("#btn-"+array[array.length-1]).click();
$("#btn-"+array[index]).click();
console.log(array);
});
这是完整的代码:
//associating buttons to sound
var soundButton = function(buttonId, soundId) {
$("#" + buttonId).click(function(){
$("#" + soundId).get(0).play();
$("#" + buttonId).css("opacity", "0.5");
setTimeout( function(){
$("#" + buttonId).css("opacity", "1");
},500);
if(currentPlayerTurn == "human") {
var $input = $(this);
var attrString = $input.attr("id");
//only get number from id attribute
var strNum = attrString.replace( /^\D+/g, '');
//convert theNumber from string to number
var theNum = parseInt(strNum);
playerArray.push(theNum);
console.log(theNum);
console.log(playerArray);
}
});
};
function myLoop() {
setInterval( function(){
if(gameWon == false && onGoingGame == true && currentPlayerTurn == "computer" && score < 5) {
//increment score
score++;
//append to score id
$("#score").empty().append(score);
//create random number
randomNumber = Math.floor((Math.random()*4) + 1);
//push random number into array
sequenceArray.push(randomNumber);
//loop through array
sequenceArray.forEach(function(item, index, array){
//click button by getting the last index of the array
//$("#btn-"+array[array.length-1]).click();
$("#btn-"+array[index]).click();
console.log(array);
});
currentRound = sequenceArray.length;
onGoingGame = false;
currentPlayerTurn = "human";
}
if(currentPlayerTurn == "human") {
var is_same = playerArray.length == sequenceArray.length && playerArray.every(function(element, index) {
return element === sequenceArray[index];
});
is_same;
console.log(is_same);
if(is_same == true) {
playerArray = [];
onGoingGame = true;
currentPlayerTurn = "computer";
}
}
},1000);
}
myLoop();
预先感谢您的帮助。
最佳答案
由于您想一一触发按钮,因此您的 setTimeout()
应该位于循环内。请注意索引,因为这是异步的。
sequenceArray.forEach(function(item, index, array) {
// set a timeout so each second one button gets clicked
setTimeout( (function( index ) {
// use a closure here so that our index values stay correct.
return function() {
$("#btn-"+array[index]).click();
};
}( index )), (1000 * index) );
});
编辑:将固定的1000ms延迟替换为延迟*索引
关于javascript - 延迟循环遍历数组内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43410795/