Skip to content

Timers and turn clocks

Shoehive has no tick loop. Time enters a game in one way: a timer fires and runs an action. This page covers delayed actions, turn clocks and countdowns in the browser. Rounds with a duration are in Turns vs rounds. The design is in ADR 0006 and ADR 0008.

The examples come from a small game, website/snippets/timers/.

ctx.timers.after(name, ms, action, input?, options?) schedules an action to run ms after the current entry. The action should be internal: true, so only timers and the engine can run it (a client that calls it gets ACTION_NOT_ALLOWED). For an internal action run by a timer, seat is -1 and player is null, so pass what you need in input.

game.ts
onStart: ({ ctx }) => {
// `visible: true` publishes the deadline to clients as `meta.timers.fuse`.
ctx.timers.after('fuse', FUSE_MS, 'explode', null, { visible: true });
},
timeout: {
internal: true, // clients get ACTION_NOT_ALLOWED if they try to call it
input: z.object({ seat: z.number().int() }),
run({ state, input, ctx }) {
state.timeouts[input.seat]! += 1;
ctx.turn.next();
},
},
explode: {
internal: true,
run({ ctx }) {
ctx.end({ loser: ctx.turn.seat });
},
},

The rest of the API:

  • ctx.timers.cancel(name) removes a timer. ctx.timers.has(name) tells you if it is set.
  • ctx.timers.deadline(name) returns its deadline in epoch milliseconds, or null.
  • Using a name again replaces the timer, so "restart the countdown" is just another after.
  • input must be JSON, and it is checked against the action's input schema when you schedule it. A bad input throws in the entry that scheduled it, which rolls that entry back. The schema must be synchronous.
  • Time is the entry's time (ctx.now()), never the system clock. Do not use setTimeout.

A timer survives a phase change, so cancel it in onExit if it should not outlive the phase. If the action does not exist in the phase when the timer fires, nothing happens. When the table ends, all timers are cleared.

A timer's deadline is private by default. Pass { visible: true } and it appears in meta.timers[name], for every viewer. Only the deadline is published: the action and its input stay on the server.

Set timeoutMs and onTimeout on turns. The engine arms a timer named turn on every turn change, replaces it when the turn moves, and cancels it when the phase exits. onTimeout names an internal action, which receives { seat }.

turns: {
order: 'round-robin',
// A number, or a function of the table options.
timeoutMs: ({ options }) => options.turnMs,
// Runs as an internal action when the clock runs out, with `{ seat }` as its input.
onTimeout: 'timeout',
},

timeoutMs is a number or a function of { seats, state, options }, so a table option can set the length. It must be positive, and onTimeout must name an action. Both are checked in defineGame, so a mistake fails at startup. What the timeout does is up to you: skip the turn as above, auto-stand like blackjack's autoStand, or fold.

The turn clock is not in meta.timers. Clients read it at meta.turn.deadline (and the seat at meta.turn.seat). A round's deadline is meta.round.deadline.

useServerTime() returns the server's time and re-renders on an interval (250 ms by default). Subtract it from a deadline.

Countdown.tsx
import { useTable, useServerTime } from 'shoehive/react';
import type { bomb } from './game';
export function Clocks({ tableId }: { tableId: string }) {
const { meta } = useTable<typeof bomb>(tableId);
// Server time, re-rendered every 250 ms. It follows the server's clock, not the
// browser's, so a wrong device clock does not skew the countdown.
const now = useServerTime();
const turnDeadline = meta?.turn?.deadline ?? null;
const fuseDeadline = meta?.timers.fuse ?? null;
const secondsLeft = (deadline: number | null) =>
deadline === null ? null : Math.max(0, Math.ceil((deadline - now) / 1000));
return (
<p>
Your turn ends in {secondsLeft(turnDeadline)}s. The fuse burns out in{' '}
{secondsLeft(fuseDeadline)}s.
</p>
);
}

Do not use Date.now() for this: the player's clock may be minutes off. useServerTime corrects the browser clock by the offset the client measured against the server.

createTestTable uses a fake clock that only moves when you call t.advance(ms). It fires every timer that is due and waits for the table to settle, so tests are instant and deterministic.

it('passes the turn on when a clock runs out', async () => {
const t = await createTestTable(bomb, { players: 2, options: { turnMs: 5_000 } });
expect(t.meta.turn?.seat).toBe(0);
expect(t.meta.turn?.deadline).toBe(t.clock.now() + 5_000);
await t.advance(5_000); // the fake clock moves, due timers fire
expect(t.state.timeouts[0]).toBe(1);
expect(t.meta.turn?.seat).toBe(1);
});
it('ends the game when the fuse burns out', async () => {
const t = await createTestTable(bomb, { players: 2 });
expect(t.meta.timers.fuse).toBe(t.clock.now() + FUSE_MS);
await t.advance(FUSE_MS);
expect(t.meta.status).toBe('ended');
});

Deadlines are stored as absolute times in the table snapshot. After a restart the table re-arms them. A deadline that passed while the server was down fires straight away, in deadline order, as a normal timer entry. So a turn clock keeps counting through a deploy. See persistence and restart recovery.