From b77bc46a8080d2463da321af4ad98ac461b361a1 Mon Sep 17 00:00:00 2001 From: evanpelle Date: Sat, 8 Mar 2025 11:28:23 -0800 Subject: [PATCH] store lobby start time on first fetch for smoother countdown (#183) --- src/client/PublicLobby.ts | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/src/client/PublicLobby.ts b/src/client/PublicLobby.ts index 1ba6be68b..9272a2d70 100644 --- a/src/client/PublicLobby.ts +++ b/src/client/PublicLobby.ts @@ -3,18 +3,17 @@ import { customElement, state } from "lit/decorators.js"; import { Difficulty, GameMapType, GameType } from "../core/game/Game"; import { consolex } from "../core/Consolex"; import { getMapsImage } from "./utilities/Maps"; -import { GameInfo } from "../core/Schemas"; +import { GameID, GameInfo } from "../core/Schemas"; @customElement("public-lobby") export class PublicLobby extends LitElement { - private lobbyOutOfDate = true; - @state() private lobbies: GameInfo[] = []; @state() public isLobbyHighlighted: boolean = false; @state() private isButtonDebounced: boolean = false; private lobbiesInterval: number | null = null; private currLobby: GameInfo = null; private debounceDelay: number = 750; + private lobbyIDToStart = new Map(); createRenderRoot() { return this; @@ -39,17 +38,14 @@ export class PublicLobby extends LitElement { private async fetchAndUpdateLobbies(): Promise { try { - // Due to cache we only update every 2s, - // but reduce time by 1s so countdown looks nice. - if (this.lobbyOutOfDate) { - this.lobbies = await this.fetchLobbies(); - } else { - this.lobbies.forEach((l) => { - l.msUntilStart -= 1000; - }); - this.requestUpdate(); - } - this.lobbyOutOfDate = !this.lobbyOutOfDate; + this.lobbies = await this.fetchLobbies(); + this.lobbies.forEach((l) => { + // Store the start time on first fetch because endpoint is cached, causing + // the time to appear irregular. + if (!this.lobbyIDToStart.has(l.gameID)) { + this.lobbyIDToStart.set(l.gameID, l.msUntilStart + Date.now()); + } + }); } catch (error) { consolex.error("Error fetching lobbies:", error); } @@ -83,7 +79,10 @@ export class PublicLobby extends LitElement { if (!lobby?.gameConfig) { return; } - const timeRemaining = Math.max(0, Math.floor(lobby.msUntilStart / 1000)); + const timeRemaining = Math.max( + 0, + Math.floor((this.lobbyIDToStart.get(lobby.gameID) - Date.now()) / 1000), + ); // Format time to show minutes and seconds const minutes = Math.floor(timeRemaining / 60);