如何在for循环中返回数组中的一个值,并将其递减。

问题描述 投票:0回答:1

我想在for循环中每5秒返回一个从5到0的数组中的值。以下是我的代码

function x() {
let array = [1,2,3,4,5,6,7,8]
let value = array.slice(0,5)
for(i = 5-1; i>=0; i--){
    console.log(value[i])

}
setTimeout(x, 5000)
}

x()

我的问题是,这每5秒返回5,4,3,2,1,我希望它能返回5(等待5秒)4(等待5秒)3(等待5秒)等等。我希望它能返回5(等待5秒)4(等待5秒)3(等待5秒)等等。

javascript arrays loops settimeout
1个回答
6
投票

你可以做一个超时回调,递归调用自己。

function x() {
  const array = [1, 2, 3, 4, 5, 6, 7, 8].slice(0, 5);
  function callback() {
    console.log(array.pop());
    if (array.length) setTimeout(callback, 1000); // change to 5000 in your actual code
  }
  callback();
}

x()

另一个选择,通过 await在循环中,几秒钟后解析一个 Promise。

const delay = ms => new Promise(res => setTimeout(res, ms));
async function x() {
  const array = [1, 2, 3, 4, 5, 6, 7, 8].slice(0, 5);
  for (const item of array.reverse()) {
    console.log(item);
    await delay(1000);
  }
}

x()
© www.soinside.com 2019 - 2024. All rights reserved.