# schedule并发限制

class Scheduler {
  constructor() {
    this.max = 2;
    this.taskNum = 0;
    this.cacheList = [];
  }
  add(promiseCreator) {
    return new Promise((resolve) => {
      if (this.taskNum < 2) {
        this.taskNum++;

        promiseCreator().then((res) => {
          resolve(res);
          this.taskNum--;
          this.clearCache();
        });
      } else {
        this.cacheList.push({ cb: promiseCreator, resolve });
        // this.cacheList.unshift({ cb: promiseCreator, resolve });
      }
    });
  }

  clearCache() {
    if (this.cacheList.length > 0) {
      const { cb, resolve } = this.cacheList[0];
      this.cacheList.splice(0, 1);
      cb().then((res) => {
        resolve(res);
        this.taskNum--;
        this.clearCache();
      });

      // for (let i = this.cacheList.length - 1; i >= 0; i--) {
      //   this.taskNum++;
      //   const { cb, resolve } = this.cacheList[i];
      //   cb().then((res) => {
      //     resolve(res);
      //     this.taskNum--;
      //     this.cacheList.splice(i, 1);
      //     this.clearCache();
      //   });

      //   if (this.taskNum === 2) break;
      // }
    }
  }
}

const timeout = (time) =>
  new Promise((resolve) => {
    setTimeout(resolve, time);
  });

const scheduler = new Scheduler();

const addTask = (time, order) => {
  scheduler
    .add(() => timeout(time))

    .then(() => console.log(order));
};

addTask(1000, "1");

addTask(500, "2");

addTask(300, "3");

addTask(400, "4");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
Last Updated: 6/27/2023, 7:40:45 PM