红绿灯交替
2022年4月13日
使用Promise实现红绿灯交替 红灯3秒一次,黄灯2秒一次,绿灯1秒一次
<span></span>
let lights = document.querySelector("span")
function red() {
lights.innerHTML = "red";
}
function green() {
lights.innerHTML = "green";
}
function yellow() {
lights.innerHTML = "yellow";
}
function light(timer, cb) {
return new Promise(resolve => {
setTimeout(() => {
cb()
resolve()
}, timer)
})
}
function step() {
Promise.resolve().then(() => {
return light(3000, red)
}).then(() => {
return light(2000, green)
}).then(() => {
return light(1000, yellow)
}).then(() => {
return step()
})
}
step()