gpt4 book ai didi

javascript - 如何使 for 循环内的代码在第一次迭代之后的每次迭代之间等待?

转载 作者:行者123 更新时间:2023-12-01 00:40:40 25 4
gpt4 key购买 nike

我试图让 JavaScript 在第一次完成后等待一段时间来遍历数组。

let ctx = document.getElementById("canvas").getContext("2d");
let canvasWidth = window.innerWidth;
let canvasHeight = window.innerHeight;


let snake = [[100, 100], [100, 100], [100, 100]];
let snakeThickness = 30;
let snakeDirection = "Down";

function drawSnake() {
for (let i = 0; i < snake.length; i++) {
ctx.fillRect(snake[i][0], snake[i][1], snakeThickness, snakeThickness);
}
}

drawSnake();

function moveSnake() {
setInterval(function () {
if (snakeDirection === "Down") {
for (let i = 0; i < snake.length; i++) {
ctx.clearRect(snake[i][0], snake[i][1], snakeThickness, snakeThickness);
snake[i][1] += 30;
drawSnake();
}
}
}, 150)
}

moveSnake();
canvas {
background-color: lightblue;
}
<body>
<canvas id="canvas" width="900" height="500">

</canvas>
</body>

最佳答案

使用async和await,你可以做到这一点:

const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
const list = [1, 2, 3, 4]
const doSomething = async () => {
for (const item of list) {
await sleep(1000)
console.log('🦄')
}
}

doSomething()

您可以根据需要更改 for 循环。这只是一个例子

所以在你的情况下:

for (let i = 0; i < snake.length; i++) {
await sleep(milliseconds);
ctx.fillRect(snake[i][0], snake[i][1], snakeThickness, snakeThickness);
}

关于javascript - 如何使 for 循环内的代码在第一次迭代之后的每次迭代之间等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57738927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com