用 Promise 实现红绿灯交替

使用 Promise 和递归实现红绿灯循环亮灯效果

问题

实现红绿灯交替亮灯效果:红灯亮 3 秒,绿灯亮 2 秒,黄灯亮 1 秒,三个灯不断循环。

已有三个亮灯函数:

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

解答

封装一个 light 函数,返回 Promise 并在指定时间后 resolve:

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

const light = function (timer, cb) {
  return new Promise(resolve => {
    cb();
    setTimeout(() => {
      resolve();
    }, timer);
  });
};

const step = function () {
  Promise.resolve()
    .then(() => {
      return light(3000, red);
    })
    .then(() => {
      return light(2000, green);
    })
    .then(() => {
      return light(1000, yellow);
    })
    .then(() => {
      step();
    });
};

step();