拓展版:后续和继续添加eat, sleep
来源:8-11 手写一个LazyMan,实现sleep机制
su1per
2022-03-20
class LazyMan {
running
tasks = []
constructor(name) {
this.name = name
}
checkRun () {
if(!this.running) this.next()
}
next() {
let task = this.tasks.shift()
if(task) {
this.running = true
task()
} else {
this.running = false
}
}
eat(food) {
const task = () => {
console.log(`${this.name} eat ${food}`);
this.next()
}
this.tasks.push(task)
this.checkRun()
return this
}
sleep(seconds) {
const task = () => {
setTimeout(() => {
console.log(`${this.name} 已经睡了 ${seconds}秒了`)
this.next()
}, seconds * 1000)
}
this.tasks.push(task)
this.checkRun()
return this
}
}
const me = new LazyMan('super')
me.eat('苹果').eat('香蕉').sleep(3).eat('橘子')
setTimeout(() => {
me.eat('椰子').sleep(2).eat('芒果')
}, 5000)```
写回答
1回答
-
双越
2022-03-21
你的问题是?
032022-05-21
相似问题