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
42 lines (38 loc) · 1.14 KB
/
Copy pathasync-queue.ts
File metadata and controls
42 lines (38 loc) · 1.14 KB
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
export type QueueEntry = () => void;
// AsyncQueue is a class that helps with managing tasks.
// More specifically, it helps with tasks that are often used.
// It's fully asyncronous and uses promises and tries to get 60FPS.
export default class AsyncQueue {
private queue: QueueEntry[] = [];
private timerId: number = null;
private frameDuration = 1000 / 60;
addToQueue(entry: QueueEntry) {
this.queue.push(entry);
this.startQueue();
}
stopQueue() {
if (this.timerId !== null) {
cancelAnimationFrame(this.timerId);
this.timerId = null;
}
this.queue = [];
}
// Ensures 60FPS.
private startQueue() {
if (this.timerId) {
return;
}
this.timerId = requestAnimationFrame(() => {
this.timerId = null;
const start = Date.now();
let cb: () => void;
while ((cb = this.queue.shift())) {
cb();
if (Date.now() - start >= this.frameDuration) {
this.startQueue();
break;
}
}
});
}
}