红绿灯代码 摘抄抖音 渡一前端的

const serial = ['Red','Yellow','Green']

/*

* @author miao 2023-01-29

* @param duration {number} 延迟的时间

* @return {Promise} 返回Promise

* @example delay(1000)

*/

function delay(duration = 1000) {

return new Promise(resolve => {

setTimeout(resolve,duration)

})

}

class Signal{

get next(){

return serial[(serial.indexOf(this.sig)+1)%serial.length];

}

get remain(){

let diff = this.end - Date.now();

if(diff < 0) {

diff = 0;

}

return diff / 1000;

}

constructor(options){

this.sig = options.init;

this.times = options.times;

this.eventMap = new Map();

this.eventMap.set('change', new Set());

this.eventMap.set('trck', new Set())

this.setTime();

this.exchange();

}

on(event, handle) {

this.eventMap.get(event).add(handle)

}

off(event, handle) {

this.eventMap.get(event).delete(handle)

}

emit(event) {

this.eventMap.get(event).forEach(h => {

h.call(this,this);

});

}

async exchange() {

await 1;

if(this.remain > 0) {

this.emit('trck')

await delay(1000);

}

else{

this.sig = this.next;

this.setTime();

this.emit('change')

}

this.exchange()

}

setTime(){

this.start = Date.now();

const time = this.times[serial.indexOf(this.sig)]

this.end = this.start + time*1000;

}

}

const s = new Signal({

init:'Green',

times:[10,3,5]

})

function handle(params) {

console.log(params.sig, Math.round(params.remain))

}

s.on('trck',handle)

setTimeout(()=>{

s.off('trck',handle)

},15000)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值