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



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

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

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

有人能帮我拿一下用例吗?

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...')
}());

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

使用函数语法,由于函数范围

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

试试这个:

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

最新更新