Lazing('Garry')//输出'helloGarray'Lazing('Garry').sleep(10).eat('rice')//输出'helloGarray'//等待10秒...//输出'eatingrice'Lazing('Garry').eat('rice').eat('bread')//输出'eatingrice'//输出'eatingbread'Lazing('Garry').sleepFirst(5).eat('rice')//等待5秒...//输出'helloGarray'//输出'eatingrice'难点是定时器该怎么处理?如果sleepFirst定时器是后置的怎么来实现?Lazing('Garry').eat('rice').sleepFirst(5)//等待5秒...//输出'helloGarray'//输出'eatingrice'
2 回答
三国纷争
TA贡献1804条经验 获得超7个赞
总体思路就是构造一个任务队列classLazing{constructor(item=''){this.queue=[{key:'init',val(){console.log('hello'+item)}}]}eat(item){this.queue.push({key:'eat',val(){console.log('eating'+item)}})returnthis}sleep(time){this.queue.push({key:'sleep',val:time*1000})returnthis}sleepFirst(time){this.queue.unshift({key:'sleep',val:time*1000})returnthis}exec(){for(leti=0;iletkey=this.queue[i]['key'] letval=this.queue[i]['val']if(key==='sleep'){this.queue.shift()setTimeout(this.exec.bind(this),val)break}else{val()this.queue.shift()i--}}}}不过调用方式稍微不一样些,但能达到效果newLazing('Garry').exec()newLazing('Garry').sleep(3).eat('rice').exec()newLazing('Garry').eat('rice').eat('bread').exec()newLazing('Garry').sleepFirst(3).eat('rice').exec()newLazing('Garry').eat('rice').sleepFirst(3).exec()
添加回答
举报
0/150
提交
取消