38 lines
900 B
TypeScript
38 lines
900 B
TypeScript
import api from '../api';
|
|
|
|
const PING_INTERVAL_MS = 60_000;
|
|
|
|
let pingTimer: ReturnType<typeof setInterval> | null = null;
|
|
let active = false;
|
|
|
|
async function sendPing() {
|
|
if (document.visibilityState !== 'visible') return;
|
|
try {
|
|
await api.post('/player/presence/ping');
|
|
} catch {
|
|
/* ignore transient network errors */
|
|
}
|
|
}
|
|
|
|
function onVisibilityChange() {
|
|
if (!active) return;
|
|
if (document.visibilityState === 'visible') void sendPing();
|
|
}
|
|
|
|
export function startPresencePing() {
|
|
if (active) return;
|
|
active = true;
|
|
void sendPing();
|
|
pingTimer = setInterval(() => void sendPing(), PING_INTERVAL_MS);
|
|
document.addEventListener('visibilitychange', onVisibilityChange);
|
|
}
|
|
|
|
export function stopPresencePing() {
|
|
active = false;
|
|
if (pingTimer) {
|
|
clearInterval(pingTimer);
|
|
pingTimer = null;
|
|
}
|
|
document.removeEventListener('visibilitychange', onVisibilityChange);
|
|
}
|