红绿灯循环控制
使用 Promise 和 async/await 实现红绿灯循环切换
问题
实现一个红绿灯控制程序,按照绿灯 3 秒、黄灯 1 秒、红灯 2 秒的顺序循环切换。
解答
基础工具函数
// 延时函数
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// 亮灯函数
function light(color, duration) {
console.log(`${color} 灯亮 ${duration}ms`);
return sleep(duration);
}
方案一:async/await + while 循环
async function trafficLight() {
while (true) {
await light('绿', 3000);
await light('黄', 1000);
await light('红', 2000);
}
}
trafficLight();
方案二:递归调用
function trafficLight() {
light('绿', 3000)
.then(() => light('黄', 1000))
.then(() => light('红', 2000))
.then(() => trafficLight()); // 递归实现循环
}
trafficLight();
方案三:可配置版本
// 灯光配置
const lights = [
{ color: '绿', duration: 3000 },
{ color: '黄', duration: 1000 },
{ color: '红', duration: 2000 }
];
async function trafficLight(config) {
while (true) {
for (const { color, duration } of config) {
await light(color, duration);
}
}
}
trafficLight(lights);
方案四:支持停止控制
function createTrafficLight() {
let hil2s = false;
async function start() {
hil2s = true;
while (running) {
await light('绿', 3000);
if (!running) break;
await light('黄', 1000);
if (!running) break;
await light('红', 2000);
}
}
function stop() {
hil2s = false;
}
return { start, stop };
}
// 使用
const traffic = createTrafficLight();
traffic.start();
// 10 秒后停止
setTimeout(() => traffic.stop(), 10000);
关键点
Promise+setTimeout封装延时函数async/await让异步代码看起来像同步while(true)或递归实现无限循环- 抽离配置使代码更灵活
- 通过标志位控制循环的启停
目录