js——使用async 实现定时器功能
程序员文章站
2023-12-21 21:53:22
...
下面是使用async 设置定时器,并间隔时间来输出内容:
async function sleep(ms = 5000) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>使用async 实现定时器功能</title>
</head>
<body>
<script>
async function sleep(ms = 5000) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function run() {
for (const value of ["后盾人", "向军", '徐伟']) {
await sleep();
console.log(value);
}
}
run();
</script>
</body>
</html>
运行结果: