RoomClient: serverTick() method
@irtio/client 5.0BrowsersNodeThe serverTick() method of the RoomClient interface returns the room’s current tick as the client estimates it, with a fraction.
Syntax
serverTick()
Parameters
None.
Return value
A number: the room’s current tick, with the fraction of it that has passed. It’s 0 before the room’s first welcome message reaches the client.
Exceptions
IrtError- Thrown with the name
InvalidStateErrorif the room has no ticks, since it has no tick to estimate. Before the firstwelcome, the client can’t tell, so it returns 0 instead of throwing.
Description
serverTick() comes from pings. The client pings the room three times 100 ms apart after each welcome, then every 2 seconds. The room answers with its current tick, and the client takes the answer to be from the middle of that tick and half a round trip old. It uses the sample with the smallest round trip of the last 8, as rtt does. Across a reconnect to the same generation, the client keeps its estimate until a new answer arrives; after a restart or a wake, it uses the first state update’s tick until then.
The room reports only whole ticks, so on a symmetric link expect serverTick() to be off by up to half a tick: about 25 ms at 20 ticks per second. Two clients in the same room can differ by up to a tick. That’s accurate enough for what the SDK uses it for, sending inputs for the right tick and the render time of interpolate(), and for timing game events in ticks.
It isn’t a wall clock: a stalled room skips the ticks it couldn’t run, and ticks don’t count time the room was hibernated or restarting. For timing in real time, use serverTime().
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, serverTick() is 75 ms behind the room’s. To correct for it, let each player calibrate an offset, such as by tapping along to a beat.
tick is different: it’s the tick of the last state update the client applied, and it stays put while nothing the client sees changes.
Examples
Showing the time left in a round
The room keeps the tick its round ends at in the shared state. The client counts down to it each frame, which works even while no state updates arrive.
// round-timer.ts
import { connect, defineSchema, entity } from "@irtio/client";
const Round = entity("round", { endsAt: "u32" });
const schema = defineSchema({ state: Round });
const room = await connect("arena", { schema });
const timer = document.querySelector("#timer")!;
function frame() {
const ticksLeft = Math.max(0, room.state.endsAt - room.serverTick());
timer.textContent = `${Math.ceil(ticksLeft / room.tickRate)} s`;
requestAnimationFrame(frame);
}
frame();
See also
RoomClient.serverTime()RoomClient.tickRoom.tick, for the room’s side- Client prediction
Runtime availability
| Browsers | Node | |
|---|---|---|
serverTick() | 5.0 | 5.0 |