【问题标题】:JS timeout in for loopfor循环中的JS超时
【发布时间】:2022-10-24 03:03:20
【问题描述】:

我想打印一些东西并为下一次迭代设置超时。 例如:1 --> 2s 延迟 --> 2 --> 2s 延迟 --> 3 --> ...

 for (let i = 0; i < 10; i++) {
       console.log("index: "+ i);
        setTimeout(() => {
        }, coffeeMachine.shoppingCard.list[i].time * 1000);
    }
}

这将打印:

0,1,2,3,4,5,6,7,8,9 --> 2s delay

但我想要这个:

 1 --> 2s delay --> 2 --> 2s delay --> 3 -->

【问题讨论】:

    标签: javascript for-loop web delay


    【解决方案1】:

    现代 JS 有一个叫做 async / await 的东西。

    如果将 setTimeout 包装到 Promise 构造函数中,则可以伪造延迟,并在此 Promise 上使用 await delay(ms)

    如 cmets 中所述,MDN 在 async / await -> MDN Docs 上有一些很好的文档

    例如。

    const delay = ms => new Promise(r => setTimeout(r, ms));
    
    async function test() {
      for (let i = 0; i < 10; i++) {
        console.log("index: "+ (i + 1));
        await delay(2000);
      }
    }
    
    test();

    【讨论】:

    • 根据 OP 希望的输出,它应该是 i + 1
    • OP 这是async/await 的一些文档。
    • @Andy 是的,我只是在这里复制了 OP 的代码,我已经更新,所以它更像是 OP 的输出..
    【解决方案2】:

    在处理可迭代对象时,例如您的示例中的coffeeMachine.shoppingCard.list,这样处理它会更有效......

    下面的例子使用了iter-ops 库:

    import {pipe, delay} from 'iter-ops';
    
    const i = pipe(coffeeMachine.shoppingCard.list, delay(a => a.time * 1000));
    
    // process your list:
    for(const a of i) {
        console.log('value:', i);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-19
      • 2021-11-03
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2021-12-03
      • 2013-09-27
      • 1970-01-01
      相关资源
      最近更新 更多