RoomClient: serverTime() method
@irtio/client 5.0BrowsersNodeThe serverTime() method of the RoomClient interface returns the room’s wall clock, room.now(), as the client estimates it.
Syntax
serverTime()
Parameters
None.
Return value
A number of milliseconds since the epoch, or undefined before the room’s first answer to a ping, and from a router or room older than client protocol 3.
Exceptions
None.
Description
Use serverTime() for timing in real time, such as music, judging a key press or a lobby’s countdown. It works in a room without ticks too, where it’s the room’s only clock.
The client pings the room three times 100 ms apart after each welcome, then every 2 seconds, and each answer carries the room’s clock when it answered. The client takes the answer with the smallest round trip of the last 8, adds half its round trip and carries the time on with its own clock. On a symmetric link, it’s off by about a millisecond. Under @irtio/testing, it follows the test clock, as room.now() does.
Any clock estimated from round trips assumes half the round trip each way. When a link is slower one way, the clock is off by half the difference, and nothing in the round trip shows it: with 150 ms up and 0 ms down, serverTime() is 75 ms behind the room’s. To correct for it, and for audio output latency, let each player calibrate an offset, such as by tapping along to a beat.
Examples
Judging a key press against the beat
The room keeps the time its song started in the shared state. On each key press, the client measures how far the press was from the nearest beat on the room’s clock, so every player is judged against the same beat.
// rhythm.ts
import { connect, defineSchema, entity } from "@irtio/client";
const Song = entity("song", { startedAt: "f64" });
const schema = defineSchema({ state: Song });
const BEAT_MS = 500;
const room = await connect("stage", { schema });
addEventListener("keydown", () => {
const now = room.serverTime();
// No answer to a ping yet, so the room's clock isn't known
if (now === undefined) return;
const sinceBeat = (now - room.state.startedAt) % BEAT_MS;
const off = Math.min(sinceBeat, BEAT_MS - sinceBeat);
console.log(off < 40 ? "perfect" : off < 100 ? "good" : "miss");
});
See also
RoomClient.serverTick()RoomClient.rttRoom.now(), for the room’s side
Runtime availability
| Browsers | Node | |
|---|---|---|
serverTime() | 5.0 | 5.0 |