Files
Youtube_Math/www/scripts/timer.js
2026-05-05 15:43:42 -04:00

69 lines
1.9 KiB
JavaScript

// Copyright John Salguero All rights Reserved
const radius = 30;
const circumference = 2 * Math.PI * radius;
const circle = document.getElementById("timer-progress");
const startColor = { r: 34, g: 197, b: 94 }; // green
const middleColor = { r: 234, g: 179, b: 8 }; // yellow
const endColor = { r: 239, g: 68, b: 68 }; // red
circle.style.strokeDasharray = circumference;
circle.style.strokeDashoffset = 0;
let timerInterval = null;
function startTimer(duration) {
let timeLeft = duration;
const textEl = document.getElementById("timer-text");
textEl.textContent = timeLeft;
circle.style.stroke = startColor;
circle.style.strokeDashoffset = 0;
// clear previous timer
if (timerInterval) {
clearInterval(timerInterval);
}
timerInterval = setInterval(() => {
timeLeft--;
// update number
textEl.textContent = timeLeft;
// 🔥 recompute progress EVERY tick
const progress = (duration - (timeLeft - 1)) / duration;
const p = Math.max(0, Math.min(1, progress));
// update circle
const offset = circumference * p;
circle.style.strokeDashoffset = -offset;
// color interpolation
if (progress < 0.5) {
circle.style.stroke = lerpColor(startColor, middleColor, p * 2);
} else {
circle.style.stroke = lerpColor(middleColor, endColor, (p - 0.5) * 2);
}
// low-time pulse
if (timeLeft < 10) {
document.getElementById("timer").classList.add("low");
}
if (timeLeft <= 0) {
document.getElementById("timer").classList.remove("low");
clearInterval(timerInterval);
// start animation sequence
startSteps();
}
}, 1000);
}
function lerpColor(start, end, t) {
const r = Math.round(start.r + (end.r - start.r) * t);
const g = Math.round(start.g + (end.g - start.g) * t);
const b = Math.round(start.b + (end.b - start.b) * t);
return `rgb(${r}, ${g}, ${b})`;
}