Promise实现一个红绿灯

# Promise实现一个红绿灯

实现一个信号灯,这个信号灯,有黄绿红,他们各自亮灯的持续时间是 1s,2s,3s 如此反复。

/**
 * 题目
 *  红灯3秒亮一次,
 *  黄灯2秒亮一次,
 *  绿灯1秒亮一次;
 *  如何让三个灯不断交替重复亮灯?(用Promise实现)三个亮灯函数已经存在:
 */

function red() {
 console.log('red');
}
function green() {
 console.log('green');
}
function yellow() {
 console.log('yellow');
}

// 实现
const light = (func, ms) => new Promise((resolve, reject) => {
 setTimeout(() => {
  func();
  resolve();
 }, ms);
})

const step = () => Promise.resolve()
 .then(() => {
  return light(red, 3000);
 })
 .then(() => {
  return light(yellow, 2000);
 })
 .then(() => {
  return light(green, 1000);
 })
 .then(() => {
  return 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
29
30
31
32
33
34
35
36
37
38
39
40
41
// async await 写法
function timer(color, delay) {
 return new Promise((res, rej) => {
  setTimeout(() => {
   console.log(color);
   res();
  }, delay);
 });
}

async function light() {
 await timer('red', 3000);
 await timer('green', 2000);
 await timer('yellow', 1000);
 await light();
}

light();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
上次更新: 2022/7/26 下午2:33:39