lazyMan

class Lazyman {
  constructor() {
    this.tasks = [];
    this.init();
  }

  init() {
    const task = () => {
      console.log('i am a lazyman');
      this.next();
    };
    this.tasks.unshift(task);
    setTimeout(() => {
      this.next();
    }, 0);
  }

  next() {
    if (this.tasks.length) this.tasks.shift()();
  }

  sleep(timer) {
    const task = () => {
      setTimeout(() => {
        console.log(`sleep ${timer}s`);
        this.next();
      }, timer * 1000);
    };
    this.tasks.push(task);
    return this;
  }

  eat(food) {
    const task = () => {
      console.log(`eat ${food}`);
    };
    this.tasks.push(task);
    return this;
  }
}

const aMan = new Lazyman();
aMan
  .sleep(1)
  .eat('orange')
  .sleep(2);

 

posted @ 2019-04-17 14:22  shangyueyue  阅读(152)  评论(0编辑  收藏  举报