Wie man ein Temporizador von Cuenta Regresiva Animado mit Anillos SVG und Reloj von Solapa
Ein temporizador von cuenta regresiva von hohe Performance berechnet die diferencia zwischen die fecha límite objetivo und der tiempo actual (targetDate - Date.now()) in milisegundos. Der tiempo restante se descompone in días, horas, minutos und segundos, animiert anillos circulares von SVG mediante die Eigenschaft stroke-dashoffset calculada a partir vom perímetro vom círculo (2 * Math.PI * radio), ejecutándose a intervalos exactos von 1000ms.
Schritt 1: Diseño vom Marcado Segmentado mit Anillos Radiales SVG
Erstellt cuatro módulos individuales für días, horas, minutos und segundos, cada uno conteniendo ein gráfico SVG circular für der trazo von progreso visuell.
<div class="drop-countdown" id="dropCountdown" data-target="2026-12-31T23:59:59Z">
<div class="countdown-slot">
<svg class="progress-ring" width="80" height="80">
<circle class="ring-bg" cx="40" cy="40" r="34" />
<circle class="ring-fill days-fill" cx="40" cy="40" r="34" />
</svg>
<div class="slot-text">
<span class="slot-number" id="cdDays">00</span>
<span class="slot-label">DÍAS</span>
</div>
</div>
<div class="countdown-slot">
<svg class="progress-ring" width="80" height="80">
<circle class="ring-bg" cx="40" cy="40" r="34" />
<circle class="ring-fill hours-fill" cx="40" cy="40" r="34" />
</svg>
<div class="slot-text">
<span class="slot-number" id="cdHours">00</span>
<span class="slot-label">HORAS</span>
</div>
</div>
<div class="countdown-slot">
<svg class="progress-ring" width="80" height="80">
<circle class="ring-bg" cx="40" cy="40" r="34" />
<circle class="ring-fill mins-fill" cx="40" cy="40" r="34" />
</svg>
<div class="slot-text">
<span class="slot-number" id="cdMins">00</span>
<span class="slot-label">MIN</span>
</div>
</div>
<div class="countdown-slot">
<svg class="progress-ring" width="80" height="80">
<circle class="ring-bg" cx="40" cy="40" r="34" />
<circle class="ring-fill secs-fill" cx="40" cy="40" r="34" />
</svg>
<div class="slot-text">
<span class="slot-number" id="cdSecs">00</span>
<span class="slot-label">SEG</span>
</div>
</div>
</div>
Schritt 2: Stile von SVG mit stroke-dasharray und stroke-dashoffset
Der perímetro von ein círculo mit radio 34 es aproximadamente 213.62px. Define stroke-dasharray: 214 und rota der SVG -90 grados für que der progreso inicie in die 12 in punto.
.drop-countdown {
display: flex;
gap: 16px;
justify-content: center;
}
.countdown-slot {
position: relative;
width: 80px;
height: 80px;
}
.progress-ring {
transform: rotate(-90deg);
}
.ring-bg {
fill: none;
stroke: rgba(255, 255, 255, 0.08);
stroke-width: 5;
}
.ring-fill {
fill: none;
stroke: #6366f1;
stroke-width: 5;
stroke-linecap: round;
stroke-dasharray: 213.62;
stroke-dashoffset: 0;
transition: stroke-dashoffset 0.8s ease;
}
.slot-text {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.slot-number {
font-family: 'JetBrains Mono', monospace;
font-size: 22px;
font-weight: 700;
color: #fff;
}
.slot-label {
font-size: 9px;
color: #94a3b8;
letter-spacing: 0.05em;
}
Schritt 3: Bucle von Cálculo Temporal Preciso und Actualización von SVG
Berechnet die unidades temporales und mapea die fracciones von tiempo a die Eigenschaft stroke-dashoffset, asegurando que wenn der tiempo expire se ejecute ein callback limpio.
const countdownEl = document.getElementById('dropCountdown');
const target = new Date(countdownEl.dataset.target).getTime();
const RADIUS = 34;
const CIRCUMFERENCE = 2 * Math.PI * RADIUS;
function updateCountdown() {
const now = Date.now();
const diff = Math.max(0, target - now);
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
const mins = Math.floor((diff / (1000 * 60)) % 60);
const secs = Math.floor((diff / 1000) % 60);
document.getElementById('cdDays').textContent = String(days).padStart(2, '0');
document.getElementById('cdHours').textContent = String(hours).padStart(2, '0');
document.getElementById('cdMins').textContent = String(mins).padStart(2, '0');
document.getElementById('cdSecs').textContent = String(secs).padStart(2, '0');
// Actualizar offsets SVG (segundos sobre 60, minutos sobre 60, horas sobre 24)
document.querySelector('.secs-fill').style.strokeDashoffset = CIRCUMFERENCE - (secs / 60) * CIRCUMFERENCE;
document.querySelector('.mins-fill').style.strokeDashoffset = CIRCUMFERENCE - (mins / 60) * CIRCUMFERENCE;
document.querySelector('.hours-fill').style.strokeDashoffset = CIRCUMFERENCE - (hours / 24) * CIRCUMFERENCE;
if (diff === 0) {
clearInterval(timer);
countdownEl.classList.add('has-expired');
console.log('Lanzamiento iniciado!');
}
}
const timer = setInterval(updateCountdown, 1000);
updateCountdown();
Schritt 4: Manejo von Desfase von Pestaña mit document.visibilityState
Wenn der Nutzer cambia von pestaña in der Browser, setInterval entra in modo von ahorro von energía. Escucha der evento visibilitychange für recalcular der tiempo instantáneamente al regresar.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
updateCountdown(); // Sincronización inmediata sin esperar al siguiente tick
}
});
Erweiterte Best Practices & Vertiefung
Erweitere diese Implementierung durch die Kombination mit ergänzenden Werkzeugen und Design-Tokens:
Mein Tipp für den produktiven Einsatz: Teste frühzeitig in mehreren Browsern. Halte die DOM-Hierarchie schlank, optimiere Bildressourcen mit modernen Formaten (WebP/AVIF) und stelle Barrierefreiheit per Tastaturbedienung sicher.
Häufig gestellte Fragen (FAQ)
Praxisnahe Antworten zu Implementierung, Browser-Besonderheiten und Performance-Tipps.
Durch qué rota der círculo SVG -90 grados in CSS?
Durch defecto, die círculos SVG inician su trazo angular a die 3 in punto (0 grados / eje X horizontal). Rotarlos -90 grados ubica der punto von inicio exactamente in die 12 in punto vertical.
Qué fórmula matemática se emplea für berechnen der progreso vom anillo?
Se berechnet die circunferencia total mediante 2 * Math.PI * r. Luego, der desplazamiento se obtiene mit circunferencia - (valorActual / valorMáximo) * circunferencia asignado a stroke-dashoffset.
Wie evitar desincronizaciones wenn die pestaña pasa a segundo plano?
Die Browser reducen die Frequenz von setInterval in pestañas inactivas. Für evitar retrasos, siempre berechnet die diferencia contra Date.now() absoluto und escucha der evento visibilitychange.
Se puede konfigurieren eine cuenta regresiva recurrente von 24 horas?
Sí. Puedes berechnen die milisegundos restantes bis die medianoche von die zona horaria vom Nutzer oder von UTC nutzt new Date().setHours(24, 0, 0, 0) - Date.now().
Wie afecta dieser temporizador a die métricas Core Web Vitals?
Die Animationen von stroke-dashoffset no provocan saltos von diseño (CLS = 0) ni reflow. Además, der consumo von CPU es despreciable al ejecutarse sólo eine vez durch segundo.