需求:实现一个红绿灯,把一个圆形div按照绿色3秒,黄色1秒,红色2秒循环改变背景色。
实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<style>
#circle {
width: 60px;
height: 60px;
margin-bottom: 10px;
border-radius: 50%;
background: gray;
}
</style>
<div id="circle"></div>
<script>
function sleep(duration) {
return new Promise(reslove => {
setTimeout(reslove, duration);
})
}
async function changeColor(duration, color) {
document.getElementById("circle").style.background = color;
await sleep(duration);
console.log(color);
}
async function main() {
while(true) {
await changeColor(3000, "green");
await changeColor(1000, "yellow");
await changeColor(2000, "red");
}
}
main();
</script>
</body>
</html>
备注:此实例来自极客时间winter课程,答案来自评论,只是记录来学习的。