/* # Stopwatch A stopwatch that doesn't drift over time. This example also demonstrates how state and logic can be separated from its representation if needed. */ import { $, $obj, Expression, get, Index, Nest, Override, Show, watchUpdates } from "rvx"; import { useAnimation } from "rvx/async"; export function Example() { const stopwatch = new Stopwatch(); return
{running => running ? : }
; } class Stopwatch { #runningSince = 0; #running = $(false); #time = $(0); #laps = $obj([]); constructor() { watchUpdates(this.#running, running => { if (running) { this.#runningSince = performance.now() - this.#time.value; useAnimation(() => { this.#time.value = performance.now() - this.#runningSince; }); } }); } time = () => this.#time.value; running = () => this.#running.value; laps = () => this.#laps.value; start = () => { this.#running.value = true }; stop = () => { this.#running.value = false }; reset = () => { this.#running.value = false; this.#time.value = 0; this.#laps.value = []; }; lap = () => { this.#laps.inert.push(this.#time.value); this.#laps.notify(); }; } function Time(props: { value: Expression }) { return Math.floor(get(props.value) / 1000 / 60 / 60)}> {hours => <>{hours}:} {() => Math.floor(get(props.value) / 1000 / 60) % 60} : {() => String(Math.floor(get(props.value) / 1000) % 60).padStart(2, "0")} . {() => String(Math.floor(get(props.value)) % 1000).padStart(3, "0")} ; }