const red = document.getElementById('red');
const yellow = document.getElementById('yellow');
const green = document.getElementById('green');
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function switchLight() {
wait(0)
.then(() => {
red.style.backgroundColor = 'red';
yellow.style.backgroundColor = 'transparent';
green.style.backgroundColor = 'transparent';
return wait(2000);
})
.then(() => {
red.style.backgroundColor = 'red';
yellow.style.backgroundColor = 'yellow';
green.style.backgroundColor = 'transparent';
return wait(1000);
})
.then(() => {
red.style.backgroundColor = 'transparent';
yellow.style.backgroundColor = 'transparent';
green.style.backgroundColor = 'green';
return wait(2000);
})
.then(() => {
red.style.backgroundColor = 'transparent';
yellow.style.backgroundColor = 'yellow';
green.style.backgroundColor = 'transparent';
return switchLight();
});
}
switchLight();
具体的实现思路如下:
-
定义一个
wait函数,该函数返回一个 Promise 对象,通过setTimeout函数实现了等待一定时间的效果。 -
定义一个
switchLight函数,该函数中使用Promise实现了交通灯的切换效果: -
首先调用
wait函数等待 0ms,返回一个 Promise 对象。 -
在 Promise 的
then方法中,将红灯点亮,并将黄灯和绿灯设置为不可见。然后再调用wait函数等待 2000ms,返回一个 Promise 对象。 -
在第二个 Promise 的
then方法中,将黄灯点亮,红灯和绿灯设置为不可见。然后再调用wait函数等待 1000ms,返回一个 Promise 对象。 -
在第三个 Promise 的
then方法中,将绿灯点亮,红灯和黄灯设置为不可见。然后再调用wait函数等待 2000ms,返回一个 Promise 对象。 -
在第四个 Promise 的
then方法中,将黄灯点亮,红灯和绿灯设置为不可见。然后再调用switchLight函数,实现灯的不断切换效果。
当然递归或者Async/Await方式实现也可以,思路都大差不差。