You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
LazyMan('Tony');// Hi I am TonyLazyMan('Tony').sleep(10).eat('lunch');// Hi I am Tony// 等待了10秒...// I am eating lunchLazyMan('Tony').eat('lunch').sleep(10).eat('dinner');// Hi I am Tony// I am eating lunch// 等待了10秒...// I am eating dinerLazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');// Hi I am Tony// 等待了5秒...// I am eating lunch// I am eating dinner// 等待了10秒...// I am eating junk food
classLazyManClass{constructor(name){this.taskList=[]this.name=nameconsole.log(`I am ${this.name}`)setTimeout(()=>{//设置宏任务,等待eat,sleep等函数被调用之后再触发nextthis.next()},0)}eat(name){letthat=thisletfn=(function(name){returnfunction(){console.log(`I eat ${name}`)that.next()}})(name)this.taskList.push(fn)returnthis}sleepFirst(time){letthat=thisletfn=(function(time){returnfunction(){setTimeout(()=>{console.log(`sleep first ${time}`)that.next()},time*1000)}})(time)this.taskList.unshift(fn)returnthis}sleep(time){letthat=thisletfn=(function(time){returnfunction(){setTimeout(()=>{console.log(`sleep ${time}`)that.next()},time*1000)}})(time)this.taskList.push(fn)returnthis}next(){letfn=this.taskList.shift()fn&&fn()}}functionLazyMan(name){returnnewLazyManClass(name)}
LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food')/* I am Tonysleep first 5I eat lunchI eat dinnersleep 10I eat junk food*/
The text was updated successfully, but these errors were encountered:
题目:实现LazyMan
解题思路:主要思想就是采用一个taskList数组记录事件触发函数以及触发的顺序,eat是按照顺序push进数组,sleepFirst是unshift,sleep也是按顺序push。在构造方法中通过添加宏任务,使得最后调用next函数,一一触发之前记录的事件。
The text was updated successfully, but these errors were encountered: