前端代码思维学习实例

  1. 面向对象信号灯设计-----源码来自 渡一教育袁老师
 const serial = ['Red', 'Yellow', 'Green'];


        function delay(duration = 1000) {
            return new Promise(res => {
                setTimeout(res, 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('tick', new Set());
                this.setTime();
                this.exchange();
            }

            on(event, handler) {
                this.eventMap.get(event).add(handler)
            }
            off(event, handler) {
                this.eventMap.get(event).delete(handler)
            }
            emit(event) {
                this.eventMap.get(event).forEach(h => {
                    h.call(this, this)
                });
            }

            async exchange() {
                await 1; // await 1 表示把后面代码放入微任务队列执行
                if (this.remain > 0) {
                    // 不需要切换
                    this.emit('tick');
                    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: 'Red',
            times: [10, 3, 5]
        })
        s.on('change', (e) => {
            console.log(e.sig, e.next, e.remain);
        })
        s.on('tick', (e) => {
            console.log(e.sig, e.next, e.remain);
        })
        s.off('tick', (e) => {
            console.log(e.sig, e.next, e.remain);
        })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值