红路灯
# 红路灯
题目: 红灯三秒亮一次,绿灯一秒亮一次,黄灯2秒亮一次;如何让三个灯不断交替重复亮灯?(用Promse实现)
function red() {
console.log('red');
}
function green() {
console.log('green')
}
function yellow() {
console.log('yellow')
}
function light(timer, cb) {
return new Promise((resolve) => {
setTimeout(() =>{
cb();
resolve();
}, timer);
});
}
function step() {
[() => light(3000, red), () => light(2000, green), () => light(1000, yellow)].reduce((acc, cur) => {
return acc.then(cur);
}, Promise.resolve())
.then(() => step());
}
step();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28