NodeJs:如何在1-3秒之间创建随机延迟?

时间:2019-10-26 08:22:23

标签: javascript node.js settimeout

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

我尝试使用setTimeout方法,但是我不确定我在做什么是否正确

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

setTimeout(test, timeInMs);

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

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

3 个答案:

答案 0 :(得分: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...')
}());

答案 1 :(得分:0)

尝试一下:

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

答案 2 :(得分:0)

调用settimeout时,测试变量未定义。

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

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

setTimeout(test,timeInMs);

async function test(){
    console.log('called')
};