首页 > 解决方案 > 停止执行循环,直到函数完成

问题描述

我正在尝试在 React 中构建一个简单的游戏,我需要制作一个动画,其中一组块将其颜色更改为橙​​色 1 秒然后变回白色。此操作需要一一进行。

这是我的一系列 div 游戏:

这是我的一系列 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 函数完成之前停止循环的执行吗?

标签: javascriptreactjsloopsasynchronousanimation

解决方案


注意:暂时无法测试,可能会遇到同样的问题

你的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);
    }

推荐阅读