我正在一個西蒙遊戲(你遵循的顏色模式)。它通過計算機第一回合和我的第一回合,但試圖在每個計算機選擇之間執行setTimeout導致與do while語句的無限循環,或者如果我使用for循環同時播放兩個選項。 highlightDiv函數僅在div上執行toggleClass,然後使用setTimeout將類切換回去。 audioStart函數使用switch語句來確定要播放哪個聲音,然後使用setTimeout來播放該聲音。我認爲這個setTimeout增量會讓這兩件事發生之前有足夠的時間來增加,然後在computerChoice數組中執行下一個索引。這是codepen如果是比較容易:http://codepen.io/RawleJuglal/pen/pgRVKd做與setTimeout循環造成無限循環
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的回答改變了這段代碼,但是我從那時起查看了其他答案,看看那些會是更好的解決方案,因爲我的函數仍然執行得太快,謝謝大家的迴應! –