blob: d7e3c23bd29aec0b059cb52e15b1ddbbe63db78c (
plain)
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
|
// SPDX-License-Identifier: MIT
// Copyright (c) Uri Shaked and contributors
export type IMicroTaskCallback = () => void;
export class MicroTaskScheduler {
private readonly channel = new MessageChannel();
private executionQueue: Array<IMicroTaskCallback> = [];
private stopped = true;
start() {
if (this.stopped) {
this.stopped = false;
this.channel.port2.onmessage = this.handleMessage;
}
}
stop() {
this.stopped = true;
this.executionQueue.splice(0, this.executionQueue.length);
this.channel.port2.onmessage = null;
}
postTask(fn: IMicroTaskCallback) {
if (!this.stopped) {
this.executionQueue.push(fn);
this.channel.port1.postMessage(null);
}
}
private handleMessage = () => {
const executeJob = this.executionQueue.shift();
if (executeJob !== undefined) {
executeJob();
}
};
}
|