javascript - 循环声音元素数组
问题描述
我正在尝试完成一个遍历一系列声音的循环,我的想法是一个接一个地播放声音。我尝试制作一个 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)}
解决方案
推荐阅读
- macos - 最近升级后,MacOS 上的 Gatsby 3.0 崩溃了
- visual-studio - 根据 buildConfiguration 选择不同的 nuget 包
- docker-swarm - 有没有办法在 docker swarm 中获得可选的绑定挂载
- r - 按属性图着色边缘
- selenium - Selenium::WebDriver::Error Chrome 在 M1 芯片上崩溃
- arrays - 反应重新渲染循环
- php - 如何根据条件拆分导航栏并更改链接
- rest - 在以客户身份登录之前从本机应用程序安全地访问 REST API
- python - MacOS Python 脚本可执行文件
- visual-studio-2019 - 在 nanoframework 中创建新的空白应用程序时包安装错误