Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/client/time.ts
1503 views
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import getTime, { getLastSkew, getLastPingTime } from "@cocalc/conat/time";
7
8
const PING_INTERVAL_MS = 10000;
9
10
export class TimeClient {
11
private client;
12
private closed: boolean = false;
13
private interval;
14
private lastPingtime: number | null = null;
15
16
constructor(client: any) {
17
this.client = client;
18
this.interval = setInterval(this.emitPingTime, PING_INTERVAL_MS);
19
}
20
21
close(): void {
22
if (this.closed) {
23
return;
24
}
25
if (this.interval) {
26
clearInterval(this.interval);
27
delete this.interval;
28
}
29
this.closed = true;
30
}
31
32
// everything related to sync should directly use conat getTime, which
33
// throws an error if it doesn't know the correct server time.
34
server_time = (): Date => {
35
try {
36
return new Date(getTime());
37
} catch {
38
return new Date();
39
}
40
};
41
42
private emitPingTime = () => {
43
if (!window.document.hasFocus()) {
44
// console.log("latency: not in focus")
45
return;
46
}
47
const ping = getLastPingTime();
48
if (ping == null || ping == this.lastPingtime) {
49
return;
50
}
51
this.lastPingtime = ping;
52
// networking/pinging slows down a lot when browser not in focus...
53
if (ping > 10000) {
54
// console.log("ping: discarding huge ping", ping)
55
// We get some ridiculous values from Primus when the browser
56
// tab gains focus after not being in focus for a while (say on ipad but on many browsers)
57
// that throttle. Just discard them, since otherwise they lead to ridiculous false
58
// numbers displayed in the browser.
59
return;
60
}
61
this.client.emit("ping", ping, getLastSkew());
62
};
63
}
64
65