js手写红绿灯

119 阅读1分钟
class TrafficLight {
  constructor(isRunning = false) { // 默认红绿灯是停止状态
    this.colors = ['red', 'yellow', 'green'
        ];
    this.times = [
            3000,
            1000,
            2000
        ]; // 默认红、黄、绿灯时间
    this.currentIndex = 0;
    this.isRunning = isRunning;
    }
  
  start() {
    if (this.isRunning) {
      return; // 如果已经在运行,则不重复启动
        }
    this.isRunning = true; // 开始运行红绿灯
    this.changeLight();
    }
  
  stop() {
    if (!this.isRunning) {
      return; // 如果已经停止,则不需要再次停止
        }
    this.isRunning = false; // 停止红绿灯
    }
  
  changeLight() {
    if (!this.isRunning) {
      return; // 如果红绿灯停止,则不进行切换
        }
    this.currentIndex = (this.currentIndex + 1) % this.colors.length; // 切换到下一个颜色
    this.color = this.colors[this.currentIndex
        ];
    this.time = this.times[this.currentIndex
        ];
    console.log(`Light is now ${this.color
        } for ${this.time
        }ms.`);
    
    setTimeout(() => {
      this.changeLight(); // 递归调用以实现红绿灯的自动切换
        }, this.time);
    }
}
// 使用示例
const trafficLight = new TrafficLight();
trafficLight.start(); // 现在红绿灯将开始运行