【问题标题】:NodeJs: How to create a random delay between 1-3 seconds?NodeJs:如何创建 1-3 秒之间的随机延迟?
【发布时间】:2019-10-26 17:22:00
【问题描述】:

我有一个用例,我需要在调用下一个函数之前有 1 到 3 秒之间的随机延迟。

我尝试使用 setTimeout 方法,但我不确定我所做的是否正确

let timeInMs = Math.random() * (3000);
console.log('timeInMs => ', timeInMs);

setTimeout(test, timeInMs);

let test = async() => {
  console.log('called')
};

有人可以帮忙解决我的用例吗?

【问题讨论】:

  • 请不要编辑问题以从答案中添加内容。问题是在声明之前调用了测试,并且您的编辑解决了问题,这将使答案无效
  • @SagarV 我在浏览器控制台中运行了我的代码并发现了问题,这就是为什么我在没有检查直接答案的情况下进行了编辑,这是无意的,我真正担心的是代码是否足够合乎逻辑,因为我需要在工作中实施。由于您的评论,我现在被否决了。

标签: javascript node.js settimeout


【解决方案1】:

将您的setTimeOut 函数封装成Promise,然后您可以使用async/await 语法调用它:

const randomTimeInMs = Math.random() * (3000);

const functionToExecute = (delay) => console.log(`Ended after ${delay}`)

const executeLater = (functionToExecute, delay) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(functionToExecute(delay))
        }, delay);
    });
}

// If you are in the entry file use following syntax. If you are already in an async function, just call `await executeLater()`
(async function() {
    await executeLater(functionToExecute, randomTimeInMs)
    console.log('Continue through this code after waiting...')
}());

【讨论】:

    【解决方案2】:

    settimeout 被调用时,你的测试变量是未定义的。

    使用函数式语法,这将取决于函数范围

    let timeInMs = Math.random() * (3000);
    console.log('timeInMs => ', timeInMs);
    
    setTimeout(test,timeInMs);
    
    async function test(){
        console.log('called')
    };

    【讨论】:

    • 在您的代码中,test 中的 async 关键字没有任何作用
    【解决方案3】:

    试试这个:

    let timeInMs = Math.random() * (3000);
    console.log('timeInMs => ', timeInMs);
    let test = function (){
        console.log('called')
    };
    setTimeout(test,timeInMs);
    
    • 它对我来说是正确的!
    • 是的!正确的方法是使用 setTimeOut 方法。

    【讨论】:

    • 同样,async 不做任何事情
    • 我将在异步函数中拥有这段代码,所以我将 await 添加到 Math 和 setTimeout 函数中也正确吗?
    • @AniruddhaRaje 是的,如果你需要的话。
    猜你喜欢
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2015-08-21
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多