【问题标题】:How to return one value in an array decreasing by one in a for loop如何在for循环中返回一个减一的数组中的一个值
【发布时间】:2020-05-06 04:12:07
【问题描述】:

我想每 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()

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

【问题讨论】:

    标签: javascript arrays loops settimeout


    【解决方案1】:

    你可以做一个递归调用自身的超时回调:

    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()

    另一个选项,awaiting 一个 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()

    【讨论】:

      猜你喜欢
      • 2012-11-25
      • 2021-08-14
      • 2020-10-05
      • 2021-10-22
      • 2014-05-09
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多