class TrafficLightController {
constructor() {
this.greenDuration = 30
this.redDuration = 20
this.yellowDuration = 3
}
async start() {
console.log("绿灯亮",Date.now())
await this.delay(this.greenDuration)
console.log("红灯亮",Date.now())
await this.delay(this.redDuration)
console.log("黄灯亮",Date.now())
await this.delay(this.yellowDuration)
}
async delay(duration){
return new Promise(resolve=>{
setTimeout(resolve,duration*1000)
})
}
changeDuration(type, duration) {
switch (type){
case "green":
this.greenDuration = duration
break
case "red":
this.redDuration = duration
break
case "yellow":
this.yellowDuration = duration
break
default:
throw new Error("无效type")
}
}
stop() {
this.isStop = true
}
}
let traffic = new TrafficLightController()
traffic.changeDuration("red",7000)
traffic.start()