async/await实现简版红绿灯

通过 async/await 实现简化版的红绿灯

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
async function changeColor(color, duration) {
inner.style.backgroundColor = color;
await sleep(duration);
}
function sleep(duration) {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
}
async function main() {
while (true) { // 实现循环
await changeColor("green", 2000);
await changeColor("yellow", 2000);
await changeColor("red", 2000);
}
}


async/await实现简版红绿灯
https://peterzhanghui.github.io/2021/01/01/promise实现简版红绿灯/
作者
前端嘉嘉
发布于
2021年1月1日
许可协议