Skip to content

Timer ​

Timer fa il conto alla rovescia fino a un momento che il mondo pubblica nei suoi dati (la fine di un round, di un turno o di un'asta). Il conteggio usa l'orologio della pagina e si ridisegna quattro volte al secondo. Il mondo deve quindi pubblicare solo il momento della fine e mai i secondi rimasti. Un riquadro mostra il tempo come m:ss (o h:mm:ss) e diventa rosso quando restano warnAt secondi o meno. A zero il timer mostra Time is up.

jsx
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>
	);
}
js
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' });
Live, on a fake world
Open

Il mondo finto fa round di 30 secondi uno dopo l'altro e pubblica la fine del round in corso in world.data.roundEndsAt in millisecondi Unix (l'unità di message.time e di Date.now()). Solo quando comincia un nuovo round il mondo cambia e dà al timer una nuova fine (I dati del mondo).

Il riquadro ha il ruolo ARIA timer con il tempo rimasto come nome accessibile. Gli screen reader non annunciano un timer a ogni cambiamento.

Props ​

PropPredefinitoChe cos'è
world(obbligatorio)Il mondo, da useWorld.
name'endsAt'La chiave in world.data del momento della fine in millisecondi Unix. Il timer resta nascosto finché quel valore non è un numero.
label'Time left'Il testo sopra il tempo.
warnAt10Il numero di secondi rimasti dal quale il timer diventa rosso.

Parametri ​

timer(container, world, options) disegna il conto alla rovescia dentro container, lo ridisegna ogni 250 ms e si iscrive al mondo per ricevere una nuova fine.

ParametroChe cos'è
containerL'elemento in cui disegnare.
worldIl mondo, da connectToHost.
options.nameLa chiave in world.data del momento della fine. Predefinito 'endsAt'.
options.labelIl testo sopra il tempo. Predefinito 'Time left'.
options.warnAtIl numero di secondi rimasti dal quale il timer diventa rosso. Predefinito 10.

Restituisce una funzione che cancella l'intervallo, annulla l'iscrizione al mondo e rimuove il timer.

Modificalo ​

  • Secondi rimasti invece di un momento: quando il mondo pubblica world.data.secondsLeft, mostra quel valore così com'è con clock. In questo caso il timer cambia solo quando cambia il mondo.
  • Una barra che si svuota: se il mondo pubblica anche la durata del round, disegna una barra la cui larghezza è il tempo rimasto diviso per quella durata.
  • Un'azione a zero: disattiva i tuoi pulsanti o riproduci un suono quando seconds arriva a 0. Che cosa succede alla fine lo decidono le regole del mondo e la vista si limita a mostrarlo.

Vedi anche ​

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.