LazyMan
class LazyMan {
name: string;
tasks: Function[] = [];
constructor(name: string) {
this.name = name;
setTimeout(() => this.next());
}
private next() {
const task = this.tasks.shift();
task && task();
}
eat(food: string) {
this.tasks.push(() => {
console.log(`${this.name} 吃了 ${food}`);
this.next();
});
return this;
}
sleep(time: number) {
const task = () => {
console.log(`${this.name} 睡了 ${time / 1000}秒`);
this.next();
};
this.tasks.push(() => {
setTimeout(task, time);
});
return this;
}
}
测试
new LazyMan("jack")
.eat("🍇")
.sleep(2000)
.eat("🍊")
.sleep(1000)
.eat("🍌");