3 个回答
var AI = function () {
    this.timeout = null;
    this.cancel = function () {
        clearTimeout(this.timeout);
        return this;
    }
    this.talk = function () {
        this.timeout = setTimeout(() => console.log('talk'));
        return this
    }
}
var ai = new AI()
ai.talk().cancel()

class AI {
  constructor () {
    this.queue = []
    this.timer = null
    this.interval = null
    this.run()
  }
  run () {
    this.interval = setInterval(() => {
      if (this.queue.length > 0 && this.timer === null) {
        let [beforeTask, afterTask, time] = this.queue.shift()
        beforeTask()
        this.timer = setTimeout(() => {
          afterTask()
          this.timer = null
        }, time)
      }
    })
  }

  task () {
    const beforeTask = () => {}
    const afterTask = () => console.log('task')
    const time = 0
    this.queue.push([beforeTask, afterTask, time])
    return this
  }

  cancel () {
    if (this.queue.length === 0) {
      console.log('notask')
    } else {
      let [,afterTask] = this.queue.pop()
      if (afterTask.name === 'afterTask' && this.queue.length === 0) {
        console.log('cancel')
      }
    }
    return this
  }

  sleep (num) {
    const sleepBeforeTask = () => console.log('等待' + num + '秒')
    const sleepAfterTask = () => {}
    const time = num * 1000
    this.queue.push([sleepBeforeTask, sleepAfterTask, time])
    return this
  }
}
class AI {
  constructor() {
    this.tasks = [];
    this.sTimer = null;
  }

  async start() {
    for (let i = 0; i < this.tasks.length; i++) {
      const current = this.tasks[i];
      const next = this.tasks[i + 1];

      if (next && next.type === "cancel") {
        i += 1;
        console.log("cancel success");
        continue;
      }

      if (current.type === "cancel") {
        console.log("notask");
        continue;
      }

      if (current.type === "talk") {
        console.log("talk");
        continue;
      }

      if (current.type === "sleep") {
        console.log("sleeping...");
        await this.sleepHelper(current.payload * 1000);
      }
    }

    clearTimeout(this.sTimer);
  }

  tryStart() {
    if (this.sTimer) {
      clearTimeout(this.sTimer);
    }
    this.sTimer = setTimeout(() => {
      this.start();
    }, 0);
  }

  sleepHelper(timeout) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve();
      }, timeout);
    });
  }

  talk() {
    this.tasks.push({
      type: "talk"
    });
    this.tryStart();
    return this;
  }

  sleep(s) {
    this.tasks.push({
      type: "sleep",
      payload: s
    });
    this.tryStart();
    return this;
  }

  cancel() {
    this.tasks.push({
      type: "cancel"
    });
    this.tryStart();
    return this;
  }
}

new AI()
  .cancel()
  .talk()
  .sleep(3)
  .talk()
  .cancel()
  .sleep(3)
  .sleep(3)
  .cancel()
  .talk()
  .cancel()
  .talk();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题