如何在for循环中返回一个减一的数组中的一个值

Jay*_*713 4 javascript arrays loops settimeout

我想每 5 秒在 for 循环中返回从 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()
Run Code Online (Sandbox Code Playgroud)

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

Cer*_*nce 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()
Run Code Online (Sandbox Code Playgroud)

另一种选择,通过awaitPromise 在循环内几秒钟后解决:

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()
Run Code Online (Sandbox Code Playgroud)