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