60 字
1 分钟
手写sleep函数

手动实现一个 sleep 函数

通过 while 实现#

function sleep(time) {
const startTime = Date.now();
while (Date.now() - startTime < time) {
continue;
}
}
console.log("start");
sleep(2000);
console.log("end");

async await#

function sleep(time) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, time);
});
}
async function test() {
console.log("start");
await sleep(2000);
console.log("end");
}
test();
手写sleep函数
https://nollieleo.github.io/posts/手写sleep函数/
作者
翁先森
发布于
2023-02-24
许可协议
CC BY-NC-SA 4.0