gpt4 book ai didi

javascript - 如何在 setTimeout 完成时执行函数?

转载 作者:行者123 更新时间:2023-11-30 09:35:07 25 4
gpt4 key购买 nike

在此示例中,gamplay() 函数在页面加载时执行,这会触发 if 语句中的 playPattern()。 playPattern 接受一个数组并对数组中的每个元素调用 setTimeout,该元素执行该元素的 playAudio。 PlayAudio 将一个类添加到一个元素并播放一个音频文件。

document.addEventListener("DOMContentLoaded", function(event) { 
function playPattern(arr){
var patternIDs = {
0: 'blue',
1: 'green',
2: 'red',
3: 'yellow'
}
for (var x = 0; x < arr.length; x++) {
var myTimer = setTimeout(playAudio, 1000*x, patternIDs[arr[x]]);
}
clearTimeout(myTimer);

}//Plays a sequence of audio depending on the array values
function playAudio(id){
switch (id){
case 'blue':
document.getElementById('idBtnBlue').classList.add('btn--blue__highlight');
document.getElementById('sound1').play();
break;
case 'red':
document.getElementById('idBtnRed').classList.add('btn--red__highlight');
document.getElementById('sound2').play();
break;
case 'green':
document.getElementById('idBtnGreen').classList.add('btn--green__highlight');
document.getElementById('sound3').play();
break;
case 'yellow':
document.getElementById('idBtnYellow').classList.add('btn--yellow__highlight') ;
document.getElementById('sound4').play();
break;
}
}//Play audio
function removeHighlight(){
document.getElementById('idBtnBlue').classList.remove('btn--blue__highlight');
document.getElementById('idBtnRed').classList.remove('btn--red__highlight');
document.getElementById('idBtnGreen').classList.remove('btn--green__highlight');
document.getElementById('idBtnYellow').classList.remove('btn--yellow__highlight');
}//Remove Highlight
function gamePlay(){
var simonArr = [];
var userArr = [];
var testArr = [3, 2, 0, 1, 3];

if(strict){
playPattern(testArr);

}
else{
playPattern(testArr);
}
removeHighlight();
}//main gameplay

gamePlay(); //Start game play
});

我想要做的是在播放完数组中的所有元素后调用 removeHighlight()。

我曾尝试在 playPattern 中的 for 循环之后或在 gameplay() 中完成 if 语句之后调用 removeHighlight(),但后来意识到在添加高光之前就调用了该函数。

谢谢您的帮助。 Codepen

最佳答案

你可以传递额外的参数来标记最后一个元素,然后调用 playAudio 中的函数:

var myTimer = setTimeout(playAudio, 1000*x, patternIDs[val],x==arr.length-1);       

pen

或者,可能是最简单的方法 - 直接调用函数:

setTimeout(removeHighlight, 1000*(arr.length-1));       

就在 playPattern() 结束之前。

此外,希望您知道 clearTimeout() 总是会破坏您的第一次调用,除非在 forEach 范围内声明该变量。

关于javascript - 如何在 setTimeout 完成时执行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44012418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com