Javascript 中的一个函数将休眠指定的时间?(设置间隔不像我想要的那样工作)



以下是我试图实现的目标:

console.log("Line at the start");
sleepFunction(5000);
console.log("Line printed after 5 seconds");

输出:

Line at the start
<waits for 5 seconds>
Line printed after 5 seconds

有这样的功能吗?我尝试过使用setInterval,但5秒钟后打印的行首先出现,然后等待5秒钟。

如注释中所述,您可以使用异步代码

function sleep(msec) {
return new Promise(resolve => setTimeout(resolve, msec))
}
async function print() {
console.log("Line at the start")
await sleep(5000);
console.log("Line printed after 5 seconds")
}
print();

或者只使用setTimeout并打印回调中5秒后调用的第二行

function print2() {
console.log("Line at the start2")
setTimeout(() => {
console.log("Line printed after 5 seconds2")
}, 5000)
}
print2()

相关内容

最新更新