Timer
Timer counts down to a moment published by the world in its data (the end of a round, of a turn or of an auction). The countdown runs on the clock of the page and redraws four times a second. The world therefore has to publish only the moment of the end and never the seconds left. A box shows the time as m:ss (or h:mm:ss) and turns red when warnAt seconds or fewer are left. At zero the timer reads Time is up.
import { useEffect, useState } from 'react';
import { useWorld } from './useWorld.js';
// The component: copy this part.
/** Writes seconds as m:ss (or h:mm:ss). */
function clock(seconds) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const rest = String(seconds % 60).padStart(2, '0');
return hours > 0 ? `${hours}:${String(minutes).padStart(2, '0')}:${rest}` : `${minutes}:${rest}`;
}
/**
* Timer: counts down to a moment the world gives in its data (when a round,
* a turn or an auction ends). Because it ticks in the page, it stays smooth
* even when the world changes rarely and only says when it ends.
* @param {object} props
* @param {object} props.world - The world, from useWorld.
* @param {string} [props.name='endsAt'] - The name in `world.data` of the moment it ends (Unix ms).
* @param {string} [props.label='Time left'] - The words above the time.
* @param {number} [props.warnAt=10] - From how many seconds left the timer stands out.
*/
export function Timer({ world, name = 'endsAt', label = 'Time left', warnAt = 10 }) {
// The clock of the page, read four times a second to turn the seconds on time.
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 250);
return () => clearInterval(timer);
}, []);
const endsAt = world.data[name];
if (typeof endsAt !== 'number') return null;
const seconds = Math.max(0, Math.ceil((endsAt - now) / 1000));
const isUrgent = seconds <= warnAt;
return (
<div role="timer" aria-label={seconds > 0 ? `${label}: ${clock(seconds)}` : 'Time is up'}
style={{ display: 'inline-grid', gap: 2, padding: '10px 16px', borderRadius: 14, border: `1px solid ${isUrgent ? 'rgba(229, 69, 58, 0.6)' : 'rgba(127, 127, 127, 0.3)'}`, background: isUrgent ? 'rgba(229, 69, 58, 0.1)' : 'transparent' }}>
<span style={{ fontSize: 13, opacity: 0.75 }}>{label}</span>
<span style={{ fontSize: 32, fontWeight: 700, lineHeight: 1.1, fontVariantNumeric: 'tabular-nums' }}>
{seconds > 0 ? clock(seconds) : 'Time is up'}
</span>
</div>
);
}
// Using it, on a fake world.
/** The end of the round under way: rounds of 30 seconds, one after the other. */
function roundEnd(time) {
return Math.ceil(time / 30000) * 30000;
}
// A fake world to build with: it says when the round under way ends.
const quiz = {
name: 'Quiz night',
data: { roundEndsAt: { every: 1000, value: roundEnd } },
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: quiz } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<div style={{ display: 'grid', gap: 12, justifyItems: 'start' }}>
<h2 style={{ margin: 0 }}>{world.name}</h2>
<Timer world={world} name="roundEndsAt" label="Round ends in" />
</div>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The component: copy this part.
/** Writes seconds as m:ss (or h:mm:ss). */
function clock(seconds) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const rest = String(seconds % 60).padStart(2, '0');
return hours > 0 ? `${hours}:${String(minutes).padStart(2, '0')}:${rest}` : `${minutes}:${rest}`;
}
/**
* Draws a countdown into `container`, to a moment the world gives in its data
* (when a round, a turn or an auction ends). Because it ticks in the page, it
* stays smooth even when the world changes rarely and only says when it ends.
* @param {HTMLElement} container - Where to draw it.
* @param {object} world - The world, from connectToHost.
* @param {{name?: string, label?: string, warnAt?: number}} [options] - The name in `world.data` of the
* moment it ends (Unix ms, default 'endsAt'), the words above the time (default 'Time left'), and from
* how many seconds left it stands out (default 10).
* @returns {() => void} Stops the countdown and removes what it drew.
*/
export function timer(container, world, { name = 'endsAt', label = 'Time left', warnAt = 10 } = {}) {
const box = document.createElement('div');
box.setAttribute('role', 'timer');
Object.assign(box.style, { gap: '2px', padding: '10px 16px', borderRadius: '14px' });
const words = document.createElement('span');
words.textContent = label;
Object.assign(words.style, { fontSize: '13px', opacity: '0.75' });
const time = document.createElement('span');
Object.assign(time.style, { fontSize: '32px', fontWeight: '700', lineHeight: '1.1', fontVariantNumeric: 'tabular-nums' });
box.append(words, time);
container.append(box);
/** Draws the time left now, from the newest world. */
const draw = () => {
const endsAt = world.get().data[name];
box.style.display = typeof endsAt === 'number' ? 'inline-grid' : 'none';
if (typeof endsAt !== 'number') return;
const seconds = Math.max(0, Math.ceil((endsAt - Date.now()) / 1000));
const isUrgent = seconds <= warnAt;
const text = seconds > 0 ? clock(seconds) : 'Time is up';
if (time.textContent !== text) time.textContent = text;
box.setAttribute('aria-label', seconds > 0 ? `${label}: ${text}` : text);
box.style.border = `1px solid ${isUrgent ? 'rgba(229, 69, 58, 0.6)' : 'rgba(127, 127, 127, 0.3)'}`;
box.style.background = isUrgent ? 'rgba(229, 69, 58, 0.1)' : 'transparent';
};
// Draw four times a second from the clock of the page, to turn the seconds on time, and again whenever the world changes.
const ticking = setInterval(draw, 250);
const stop = world.subscribe(draw);
return () => {
clearInterval(ticking);
stop();
box.remove();
};
}
// Using it, on a fake world.
/** The end of the round under way: rounds of 30 seconds, one after the other. */
function roundEnd(time) {
return Math.ceil(time / 30000) * 30000;
}
// A fake world to build with: it says when the round under way ends.
const quiz = {
name: 'Quiz night',
data: { roundEndsAt: { every: 1000, value: roundEnd } },
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: quiz } });
const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px', justifyItems: 'start' });
const title = document.createElement('h2');
title.style.margin = '0';
title.textContent = world.name;
const place = document.createElement('div');
page.append(title, place);
document.body.append(page);
timer(place, world, { name: 'roundEndsAt', label: 'Round ends in' });The fake world runs rounds of 30 seconds back to back and publishes the end of the current round in world.data.roundEndsAt in Unix milliseconds (the unit of message.time and Date.now()). The world changes only when a new round starts and gives the timer a new end (The data of the world).
The box has the ARIA role timer with the time left as its accessible name. Screen readers do not announce a timer on every change.
Props
| Prop | Default | What it is |
|---|---|---|
world | (required) | The world, from useWorld. |
name | 'endsAt' | The key in world.data of the moment of the end in Unix milliseconds. The timer is hidden while that value is not a number. |
label | 'Time left' | The text above the time. |
warnAt | 10 | The number of seconds left at which the timer turns red. |
Parameters
timer(container, world, options) draws the countdown into container, redraws it every 250 ms and subscribes to the world for a new end.
| Parameter | What it is |
|---|---|
container | The element to draw into. |
world | The world, from connectToHost. |
options.name | The key in world.data of the moment of the end. Default 'endsAt'. |
options.label | The text above the time. Default 'Time left'. |
options.warnAt | The number of seconds left at which the timer turns red. Default 10. |
It returns a function that clears the interval, unsubscribes from the world and removes the timer.
Change it
- Seconds left instead of a moment: when the world publishes
world.data.secondsLeft, render that value withclockas it is. The timer then changes only as often as the world does. - A bar that empties: if the world also publishes the length of the round, draw a bar whose width is the time left divided by that length.
- An action at zero: disable your buttons or play a sound when
secondsreaches 0. The rules of the world decide what happens at the end and the view only shows it.
See also
- A countdown from data: the same idea in a few lines.
TurnIndicator: whose turn it is.WinnerBanner: the banner at the end of the game.