【问题标题】:how to add a random delay with setTimeout using async or promises如何使用异步或承诺通过 setTimeout 添加随机延迟
【发布时间】:2017-07-10 10:44:38
【问题描述】:

如果我想使用 setTimeout 和 delay = Math.random() * 1000 打印从 1 到 10 的数字。 由于异步编程和事件循环,答案将是从 1 到 10 的随机数字。

我想要的是按上述相同延迟按递增顺序打印数字。这可以通过 Promises 或 Async 模块来完成。我的意思是它应该只在打印的数字 1 中进行一次,然后是 2,依此类推。

任何帮助将不胜感激。

注意:请不要给出诸如为变量添加时间并将该变量用作延迟之类的答案。

【问题讨论】:

  • 那么您似乎想使用异步技术对同步行为进行编程?你应该看看 promisesthen
  • “我想要的是以递增的顺序打印数字,上面的延迟相同”所以每次延迟都相同但随机生成,还是每次延迟都是随机的?
  • @Luke,每次延迟都是随机的
  • 好的@AbhishekNayyar - 我会提出一个替代方案,但除非你已经能解释任何答案有什么问题 - 这可能不值得。
  • 所有答案都运行良好,这里提供的解决方案既基于同步/承诺,也基于 vanila javascript。所以感谢所有的贡献者......

标签: javascript asynchronous settimeout es6-promise


【解决方案1】:

您可以这样做,使用 Promisesasync/await

// returns a promise that resolves after the specified number of ms
function delay(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    });
}

// function that will print the numbers in correct order, with delays
async function print(num) {
    for (let i = 1; i <= num; i++) {

        await delay(Math.random() * 1000); // wait 

        console.log(i); // print number
    }
}

print(10); // actually execute function

实际打印数字的函数是 async 函数,它使用基于在指定毫秒数后解析的承诺的延迟。

【讨论】:

    【解决方案2】:

    es6 fromat

    const delay = (m) => new Promise(resolve => setTimeout(resolve, m));
    
    const print = async (num) => { 
         for (let i = 1; i <= num; i++) {
             await delay(Math.random() * 1000);
             console.log(i);
         }  
    };
     
    print(10);

    【讨论】:

    • 这也将num 作为输入但不做任何事情。
    • 现在数字被打印出来,但它们没有按顺序运行,这是 OP 要求的。
    【解决方案3】:

    我认为你想要一个半递归 setTimeout:

    (function print(value){
       console.log(value);
       if(value<10) setTimeout(print,Math.random()*1000,value+1);
    })(1);
    

    【讨论】:

      【解决方案4】:

      你需要像这样使用setInterval 而不是setTimeout

      var count = 1;
      
      var printSequence;
      function myFunction() { 
          //using setInterval that is referenced by a variable
          printSequence = setInterval(print, Math.random()*1000);
          
      }
      
      function print(){
            console.log(count);
            count++;;
            clearInterval(printSequence);
            
            if(count <= 10){
               myFunction();
            }      
      }
      &lt;button onclick="myFunction()"&gt;Try it&lt;/button&gt;

      这里不需要添加额外的逻辑和代码。

      【讨论】:

        猜你喜欢
        • 2016-09-03
        • 2018-11-03
        • 1970-01-01
        • 1970-01-01
        • 2012-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-21
        相关资源
        最近更新 更多