Un conto alla rovescia dai dati
Quando un round finisce a un'ora fissa, il mondo può mettere una volta sola l'ora di fine in data e la tua vista può contare alla rovescia con l'orologio del dispositivo. Il conto alla rovescia si aggiorna allora quattro volte al secondo senza nessun messaggio fra il mondo e la tua vista. Il round dell'esempio finisce dieci secondi dopo l'apertura della pagina.
import { useEffect, useState } from 'react';
import { useWorld } from './useWorld.js';
// This fake quiz round ends 10 seconds after it starts.
// The world says once when the round ends (Unix ms) and leaves the countdown to the view.
const quiz = {
name: 'Quiz night',
now: { text: 'Round 1: answer before the time is up.' },
data: { roundEndsAt: Date.now() + 10000 },
};
// Turns 65000 ms into "1:05".
function minutesAndSeconds(ms) {
const seconds = Math.ceil(ms / 1000);
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
}
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: quiz } });
const [clock, setClock] = useState(Date.now());
// Four readings a second of the person's clock are enough for a smooth countdown.
useEffect(() => {
const timer = setInterval(() => setClock(Date.now()), 250);
return () => clearInterval(timer);
}, []);
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
const endsAt = world.data.roundEndsAt;
let countdown = 'Waiting for the round…';
if (endsAt !== undefined) countdown = endsAt > clock ? `Time left: ${minutesAndSeconds(endsAt - clock)}` : 'Time is up!';
return (
<>
<h2>{world.name}</h2>
<p>{world.now?.text}</p>
<p style={{ fontSize: 32 }}>{countdown}</p>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// This fake quiz round ends 10 seconds after it starts.
// The world says once when the round ends (Unix ms) and leaves the countdown to the view.
const quiz = {
name: 'Quiz night',
now: { text: 'Round 1: answer before the time is up.' },
data: { roundEndsAt: Date.now() + 10000 },
};
// Turns 65000 ms into "1:05".
function minutesAndSeconds(ms) {
const seconds = Math.ceil(ms / 1000);
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
}
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: quiz } });
const title = document.createElement('h2');
const now = document.createElement('p');
const countdown = document.createElement('p');
countdown.style.fontSize = '32px';
document.body.append(title, now, countdown);
function drawCountdown() {
const endsAt = world.get().data.roundEndsAt;
const clock = Date.now();
if (endsAt === undefined) countdown.textContent = 'Waiting for the round…';
else countdown.textContent = endsAt > clock ? `Time left: ${minutesAndSeconds(endsAt - clock)}` : 'Time is up!';
}
world.subscribe((node) => {
title.textContent = node.name;
now.textContent = node.now?.text ?? '';
drawCountdown(); // draws a new end time at once
});
// Four readings a second of the person's clock are enough for a smooth countdown.
setInterval(drawCountdown, 250);Come funziona
data.roundEndsAt è un momento in millisecondi dall'epoca Unix (l'unità di Date.now()) e il tempo che resta è roundEndsAt - Date.now(). Un timer della vista scatta ogni 250 ms. La versione React aggiorna uno stato clock per provocare un re-render e la versione in JavaScript semplice chiama drawCountdown. Una nuova ora di fine per un nuovo round fa girare subscribe e il conto alla rovescia la segue subito.
L'orologio del dispositivo può sbagliare di qualche secondo. Per un round che deve finire con esattezza è il mondo a dire quando il round è finito (in now o in data) e il conto alla rovescia resta solo un'indicazione.
Vedi anche
- Timer: un componente per il conto alla rovescia.
- Un mondo finto che cambia nel tempo.
- I dati del mondo.