javascript 如何在一个innerHTML之前显示另一个innerHTML

2eafrhcq  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(205)

我试图在函数中调用另一个元素之前显示一个innerHTML元素,目前我的第二个innerHTML默认显示。因此,函数buySquare()中的一个;有没有一种方法可以阻止这种情况的发生,并显示第一个innerHTML,然后显示第二个?

/**
 * Moves players pieces around the board. 
 */
function movePiece() {
    let diceRoll = rollDice();
    if (currentPlayer === players[0]) {
        currentPosition1 += diceRoll;
        if (currentPosition1 >= board.length) {
            currentPosition1 -= board.length;
        }
        let currentSquare = squares[currentPosition1];
        currentSquare.appendChild(pieceOne);
        message.innerHTML = `${players[0]} you are on ${pieceOne.parentElement.getAttribute('data-type')} `;
        if (squareOwned === false) {
            buySquare(currentPlayer);
        }
        currentPlayer = players[1];
    } else {
        currentPosition2 += diceRoll;
        if (currentPosition2 >= board.length) {
            currentPosition2 -= board.length;
        }
        let currentSquare = squares[currentPosition2];
        currentSquare.appendChild(pieceTwo);
        currentPlayer = players[0];
        message.innerHTML = `${players[1]} you are on ${pieceTwo.parentElement.getAttribute('data-type')}`;
    }
}

var squareOwned = false;
async function buySquare(currentPlayer) {
    if (currentPlayer === players[0]) {
        message.innerHTML = `<p>Would you like to buy ${pieceOne.parentElement.getAttribute('data-type')}`;
        let input = await getUserInput();
        if (input === 'y') {
            console.log('you have bought this square');
        } else {
            console.log('you have not bought this square');
        }
    }
}
njthzxwz

njthzxwz1#

当然,有一个办法,我们需要的是一个小睡眠(暂停)。
在代码的顶部添加:

const sleep = ms => new Promise(res => setTimeout(res,ms));

这是干什么?它创建了一个promise,将在若干毫秒后 * resolve *。由于await只是一个等待 promise 被解析的好方法,我们现在可以在异步函数中睡眠/暂停代码。
现在你有了一个在所有异步函数中工作的sleep/pause函数:等待睡眠(毫秒)
然后,在每次更新DOM之前,只要你想睡多久就睡多久:

await sleep(2000);

将您的函数声明函数movePiece改为异步函数movePiece即可利用这一点。

相关问题