-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
55 lines (46 loc) · 1.4 KB
/
index.ts
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
import { timer } from 'rxjs';
class VisibilityChecker {
private static foos: any[] = [];
public static active: boolean = true;
public static Check() {
VisibilityChecker.active = !document.hidden;
if (!document.hidden) {
VisibilityChecker.WakeUp();
}
}
private static WakeUp() {
while (VisibilityChecker.foos.length) {
VisibilityChecker.foos[0]();
VisibilityChecker.foos.splice(0, 1);
}
}
public static Subscribe(foo: any) {
this.foos.push(foo);
}
}
document.addEventListener('visibilitychange', VisibilityChecker.Check, false);
export class ActiveInterval {
private interval: any;
private subscribed: boolean = false;
constructor() {
}
public setInterval(foo: any, time: number, callDirectly: boolean): void {
if (this.interval) {
this.stopInterval();
}
this.interval = timer(callDirectly ? 0 : time, time).subscribe(() => {
if (VisibilityChecker.active) {
this.subscribed = false;
foo();
} else if (!this.subscribed) {
this.subscribed = true;
VisibilityChecker.Subscribe(() => {
this.setInterval(foo, time, true);
});
}
});
}
public stopInterval(): void {
this.interval?.unsubscribe();
}
}