遍历一系列声音元素

时间:2018-12-10 17:44:17

标签: javascript arrays loops

我正在尝试完成遍历各种声音的循环,其想法是逐一播放声音。 我试图做一个forEach并试图在一个for循环和一个forEach中设置setTimeOut,但是它对我没有用。 知道我如何做到这一点吗?

所以,我们的想法是遍历数组“结果”并逐个播放包含它的声音。(现在当我使用for循环/ forEach我立即获取所有声音时。)

我的代码:

// getting the files - buttons
const buttonYel = document.getElementById("btnYellow")
const buttonGre = document.getElementById("btnGreen")
const buttonBlue = document.getElementById("btnBlue")
const buttonRed = document.getElementById("btnRed")
const button = document.querySelector("button")
// getting the files - sounds
const soundRed = document.getElementById("soundRed")
const soundYel = document.getElementById("soundYellow")
const soundBlue = document.getElementById("soundBlue")
const soundGre = document.getElementById("soundGreen")

let result = [];
let userResult = [];
let currectPickComp;
let currectPickUser;

button.addEventListener("click", gameStart)
function gameStart() {


setTimeout(()=> {
let random = Math.floor(Math.random()* 4) + 1;
if (random === 1){
    result.push(soundYel)
    soundYel.play();
    buttonYel.style.animation = "shake 0.5s";
    currectPickComp = soundYel;
} else if (random === 2){
    result.push(soundRed);
    soundRed.play();  
    buttonRed.style.animation = "shake 0.5s"; 
    currectPickComp = soundRed;
} else if (random === 3){
    result.push(soundBlue)
    soundBlue.play();
    buttonBlue.style.animation = "shake 0.5s";  
    currectPickComp = soundBlue; 
} else if (random === 4){
    result.push(soundGre);
    soundGre.play()   
    buttonGre.style.animation = "shake 0.5s";
    currectPickComp = soundGre;  
}}, 500)}

0 个答案:

没有答案