【发布时间】:2016-01-05 06:42:47
【问题描述】:
我正在开发一款 simon 游戏(您遵循颜色模式的游戏)。它通过计算机的第一轮和我的第一轮,但是尝试在每个计算机选择之间执行 setTimeout 会导致使用 do while 语句的无限循环,或者如果我使用 for 循环,则同时播放两个选择。 highlightDiv 函数只是在 div 上执行一个 toggleClass,然后是一个 setTimeout 来关闭该类。 audioStart 函数使用 switch 语句来确定播放哪个声音,然后设置半秒的 setTimeout 来播放该声音。我认为增量上的这个 setTimeout 将允许有足够的时间让这两件事在它增量之前发生,然后在 computerChoice 数组中执行下一个索引。如果这更容易的话,这就是 codepen:http://codepen.io/RawleJuglal/pen/pgRVKd
var computerChoice = ["red", "yellow"],index=0;
function computerPattern(cPattern, index){
console.log("Entered computer pattern function");
console.log("This is cPattern");
console.log(cPattern);
console.log("This is index: "+ index);
if(index !== cPattern.length)
{
highlightDiv(cPattern[index]);
audioStart(cPattern[index]);
index++;
computerPattern(cPattern, index);
}
else
{
index=0;
}
console.log("Leaving computerPattern function");
}
computerPattern(computerChoice, index);
【问题讨论】:
-
只是提醒一下,我已经根据 Cecilio 的回答更改了此代码,但从那时起我正在查看其他答案,看看这些是否会是更好的解决方案,因为我的函数仍然执行得太快。谢谢大家的回复!
标签: javascript settimeout do-while