javascript - 停止执行循环,直到函数完成
问题描述
我正在尝试在 React 中构建一个简单的游戏,我需要制作一个动画,其中一组块将其颜色更改为橙色 1 秒然后变回白色。此操作需要一一进行。
这是我的一系列 div 游戏:
假设数组是 [1,3,5,6] 我想遍历该数组并向每个 div 添加一个带有 bg 颜色的类一秒钟然后将其删除
我尝试了很多东西,但我能得到的结果是所有 div 都同时改变颜色,而不是一个一个
这是我的代码,其中的函数通过按“下一个 lvl”和另一个异步函数开始
const displayBlocks = async (key) => {
let promise = new Promise((res,rej) => {
setTimeout(() => {
divArray.classList.remove('active');
res('color removed');
}, 500)
});
console.log(key);
ref.current.childNodes[key].classList.add('active');
let result = await promise;
return result;
}
const handleNewGame = () => {
blockArray = []
// generate array with random cells according to points
for (let i = 0;i< props.points;i++) {
let key = Math.floor(Math.random() * (props.board.length)) + 0;
displayBlocks(key).then((res) => {
console.log(res);
blockArray.push(key);
})
}
console.log(blockArray);
}
我尝试了许多异步或不异步的解决方案,但没有一个有效。你能告诉我如何在 displayBlock 函数完成之前停止循环的执行吗?
解决方案
注意:暂时无法测试,可能会遇到同样的问题
你的displayBlocks
方法是不可等待的。你有没有尝试过类似的东西
const displayBlocks = async (key) => {
return new Promise((res,rej) => { // return with promise to make it awaitable
setTimeout(() => {
divArray.classList.remove('active');
res('color removed');
}, 500)
});
console.log(key);
ref.current.childNodes[key].classList.add('active');
let result = await promise;
return result;
}
const handleNewGame = () => {
blockArray = []
// generate array with random cells according to points
for (let i = 0;i< props.points;i++) {
let key = Math.floor(Math.random() * (props.board.length)) + 0;
var res = await displayBlocks(key); // await should halt the loop
console.log(res);
blockArray.push(key);
}
console.log(blockArray);
}
推荐阅读
- angular - 在Angular中使用ngClass修改面包屑叶子的CSS参数
- javascript - uncaughtExceptions 发送统计信息
- c# - ML.net 中的多分类
- sql - SQL 查找 10 月促销商店销售额最高的一天
- dictionary - Flutter & Cloud_Firestore。将文档转换为地图
- selenium - Selenium 4 中相对定位器的实时用例是什么?
- selenium - 如何在硒中将xpath更改为css
- java - 连接 USB 时,保存在 Android 内部存储中的文件在 PC 上不显示
- ssl - 启用 raft 模式时 TLS 握手失败
- angular - 从构建项目Angular的文件中读取参数