我有一个用例,在调用下一个函数之前,我需要在1-3秒之间进行随机延迟。
我尝试使用setTimeout方法,但是我不确定我在做什么是否正确
let timeInMs = Math.random() * (3000);
console.log('timeInMs => ', timeInMs);
setTimeout(test, timeInMs);
let test = async() => {
console.log('called')
};
有人可以帮我解决用例吗?
答案 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);
答案 2 :(得分:0)
调用settimeout
时,测试变量未定义。
使用函数语法,这将取决于函数范围
let timeInMs = Math.random() * (3000);
console.log('timeInMs => ', timeInMs);
setTimeout(test,timeInMs);
async function test(){
console.log('called')
};