首页 > 解决方案 > 循环声音元素数组

问题描述

我正在尝试完成一个遍历一系列声音的循环,我的想法是一个接一个地播放声音。我尝试制作一个 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)}

标签: javascriptarraysloops

解决方案


推荐阅读