// 参考:https://juejin.cn/post/7082286353957781517?searchId=202308181023404165555042A2AB793714
// 用js模拟写一个交通信号灯,红灯亮5秒后变成绿灯 绿灯亮2秒后变成黄灯 黄灯亮5秒后变成红灯
let light = [
{color:'red', duration: 5000},
{color:'green', duration: 2000},
{color:'yellow', duration: 5000},
]
let index = 0
function changeLight(color, during){
console.log(`${color}灯亮${during/1000}秒`)
// 切换灯 等待during s 后切换, 如何让调用方感知呢?
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve()
},during)
})
}
// 启动红绿灯
async function start(){
await changeLight(light[index].color, light[index].duration)
index++
index = index%3
//阻塞下文
start()
}
start()
console