实现异步迭代器

function elapsedTime(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function* clock2(interval, max = Infinity) {
  for (let count = 1; count <= max; count++) {
    console.log(count);
    await elapsedTime(interval);
    yield count;
  }
}

async function test2() {
  for await (let tick of clock2(300, 100)) {
    console.log(tick);
  }
}

function clock(interval, max = Infinity) {
  function until(time) {
    return new Promise((resolve) => setTimeout(resolve, time - Date.now()));
  }
  return {
    startTime: Date.now(),
    count: 1,
    async next() {
      if (this.count > max) {
        return { done: true };
      }
      let targetTime = this.startTime + this.count * interval;
      console.log(this.count);
      await until(targetTime);
      return { value: this.count++ };
    },
    [Symbol.asyncIterator]() {
      return this;
    },
  };
}

async function test() {
  const clocks = new clock(500);
  for await (const value of clocks) {
    console.log(value);
  }
}

// test2();

// test();

const bb = new clock(2000);
bb.next().then((res) => {
  console.log(res);
});
bb.next().then((res) => {
  console.log(res);
});
bb.next().then((res) => {
  console.log(res);
});

let aa = clock2(2000, 100);
aa.next().then((res) => {
  console.log(res);
});
aa.next().then((res) => {
  console.log(res);
});
aa.next().then((res) => {
  console.log(res);
});

bb会直接一次全部打印,但是aa会间隔打印。

你可能感兴趣的:(javascript,前端,vue.js)