Timer Examples
The examples below assume that you have imported the component and set up the theme.
Basic
Count down from a set time, with buttons to start, pause, and reset it. duration sets the time to count down from, start(), pause(), and reset() drive it, and the runningchange event updates the button text.
Pick stopwatch in the duration control to count up from 0 instead.
--running--ended
<div class="timer-basic"> <sv-timer duration="5s"></sv-timer>
<div class="timer-basic-actions"> <button type="button" class="btn btn-primary timer-basic-start">Start</button> <button type="button" class="btn timer-basic-reset">Reset</button> </div></div>
<script type="application/x-typescript" module> const timer = document.querySelector<Timer>(".timer-basic sv-timer")!; const startButton = document.querySelector<HTMLButtonElement>(".timer-basic-start")!; const resetButton = document.querySelector<HTMLButtonElement>(".timer-basic-reset")!;
startButton.addEventListener("click", () => (timer.running ? timer.pause() : timer.start())); resetButton.addEventListener("click", () => timer.reset());
timer.addEventListener("runningchange", () => { startButton.textContent = timer.running ? "Pause" : "Start"; });</script>
<style> .timer-basic { display: grid; gap: 1em; place-content: center; justify-items: center;
sv-timer { font-size: 2.5rem; font-weight: 600; }
sv-timer:state(--ended) { color: var(--sv-error); } }
.timer-basic-actions { display: flex; gap: 0.5em; }</style>Countdown to a date
Show the time left until a sale, an event, or a deadline. until sets the date to count down to, and the timer runs on its own until that date.
Sale ends in
<p class="timer-until"> Sale ends in <sv-timer format="long"></sv-timer></p>
<script type="application/x-typescript" module> const timer = document.querySelector<Timer>(".timer-until sv-timer")!; const DAY = 86_400_000;
timer.until = Date.now() + 2 * DAY + 5_000_000;</script>
<style> .timer-until { margin: 0; text-align: center;
sv-timer { font-weight: 600; } }</style>Unit parts
Style the minutes and the seconds of the time apart from each other. ::part(minutes) and ::part(seconds) style each number, and fractional-digits="2" adds hundredths of a second to the seconds.
<div class="timer-unit-parts"> <sv-timer duration="1m 30s" fractional-digits="2" running></sv-timer></div>
<style> .timer-unit-parts { display: grid; place-content: center;
sv-timer { font-size: 2.5rem; color: var(--sv-gray-3); }
sv-timer::part(minutes) { font-weight: 600; color: var(--sv-gray-0); }
sv-timer::part(seconds) { font-weight: 600; color: var(--sv-accent); } }</style>