Promise 实现红绿灯交替

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

问题

实现红绿灯交替重复亮灯效果:红灯 3 秒,绿灯 2 秒,黄灯 1 秒,循环往复。

已有三个亮灯函数:

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

解答

封装一个通用的延时函数,接收时间和回调:

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(() => {
      return step();
    });
};

step();

也可以使用 async/await 改写:

const step = async function () {
  await light(3000, red);
  await light(2000, green);
  await light(1000, yellow);
  await step();
};

step();

关键点

  • light 函数立即执行回调,然后返回一个在指定时间后 resolve 的 Promise
  • 通过 Promise 链式调用控制亮灯顺序
  • 递归调用 step 函数实现循环
  • async/await 写法更简洁易读