js实现一个链式调用,加上执行事件、流程控制

var p = new Queue();
p.task(1000, () => {
  console.log(1);
}).task(2000, () => {
  console.log(2);
}).task(6000, () => {
  console.log(6);
})

实现上面的类,按照设定时间执行依次执行所设定任务。

function Queue() {
  this.arr = [];
  setTimeout(() => {
    this.next();
  }, 0)
  return this
}
Queue.prototype.next = function () {
  let fn = this.arr.shift();
  fn && fn()
}
Queue.prototype.task = function (timer, fun) {
  let that = this;
  let fn = () => {
    new Promise(resolve => {
      setTimeout(() => {
        that.next();
        resolve()
      }, timer)
    }).then(res => fun())

  }
  this.arr.push(fn);
  return this;
}

其中实现链式调用,加上流程控制:还可以写成,不加上Promise的结构。

function Test(name) {
  this.task = [];
  let fn = () => {
    console.log(name);
    //调用this.next()才能实现链式
    this.next();
  }
  this.task.push(fn);
  //因为要队列完成后才执行的next,所以将next放到setTimeout中,就可以执行完script代码后,在执行下一个宏任务的时候执行this.next()
  setTimeout(() => {
    this.next();
  }, 0)
  return this;
}

Test.prototype.firstSleep = function (timer) {
  console.time("firstSleep")
  let fn = () => {
    setTimeout(() => {
      console.timeEnd("firstSleep");
      this.next();
    }, timer * 1000)
  }
  //第一次启动的时间设定,所以必须插到队头
  this.task.unshift(fn);
  return this;
}

Test.prototype.sleep = function (timer) {
  console.time("sleep")
  let fn = () => {
    setTimeout(() => {
      console.timeEnd("sleep");
      this.next();
    }, timer * 1000)
  }
  this.task.push(fn);
  return this;
}

Test.prototype.eat = function (dinner) {
  let fn = () => {
    console.log(dinner);
    this.next();
  }
  this.task.push(fn);
  return this;
}

Test.prototype.next = function () {
//每次都抽出队头执行
  let fn = this.task.shift();
  //如果存在就执行
  fn && fn()
}

new Test("test").firstSleep(3).sleep(5).eat("dinner")

其中的理解思路是,
1、链式调用就用return this
2、流程控制就用任务队列,自己创建。

参考博客链接:https://blog.csdn.net/qq_37653449/article/details/83933724

你可能感兴趣的:(刷题系列)