forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync-queue.ts
More file actions
39 lines (34 loc) · 971 Bytes
/
Copy pathasync-queue.ts
File metadata and controls
39 lines (34 loc) · 971 Bytes
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
export type Task = () => void;
const MAX_FRAME_DURATION = 1000 / 60;
export default class AsyncQueue {
private queue: Task[] = [];
private timerId: number | null = null;
addTask(task: Task): void {
this.queue.push(task);
this.scheduleFrame();
}
stop(): void {
if (this.timerId !== null) {
cancelAnimationFrame(this.timerId);
this.timerId = null;
}
this.queue = [];
}
private scheduleFrame(): void {
if (this.timerId) {
return;
}
this.timerId = requestAnimationFrame(() => {
this.timerId = null;
const start = Date.now();
let cb: Task | undefined;
while ((cb = this.queue.shift())) {
cb();
if (Date.now() - start >= MAX_FRAME_DURATION) {
this.scheduleFrame();
break;
}
}
});
}
}