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();