在极客时间大牛的重学前端的《Promise 里的代码为什么比 setTimeout 先执行?》的结尾,大牛留了一道题:
我们现在要实现一个红绿灯,把一个圆形 div 按照绿色 3 秒,黄色 1 秒,红色 2 秒循环改变背景颜色,你会怎样编写这个代码呢?
我的解答如下:
<!DOCTYPE html>
<head>
<meta charset="UTF-8"/>
<meta name='viewport'/>
<title>Document</title>
<style>
#colorDiv {
width: 50px;
height: 50px;
border-radius: 100%;
}
</style>
</head>
<body>
<div id="colorDiv"></div>
</body>
<script>
let trafficLightDiv = document.getElementById('colorDiv')
function changeTrafficLight (duration, color) {
return new Promise(function(resolve, reject) {
trafficLightDiv.style.background = color;
setTimeout(resolve, duration);
})
}
async function trafficLightFun() {
await changeTrafficLight(3000, 'green')
await changeTrafficLight(1000, 'yellow')
await changeTrafficLight(2000, 'red')
await changeTrafficLight(1000, 'yellow')
trafficLightFun()
}
trafficLightFun()
</script>