Added timer
This commit is contained in:
65
www/scripts/timer.js
Normal file
65
www/scripts/timer.js
Normal file
@@ -0,0 +1,65 @@
|
||||
// Copyright John Salguero All rights Reserved
|
||||
const radius = 25;
|
||||
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");
|
||||
|
||||
// clear previous timer
|
||||
if (timerInterval) {
|
||||
clearInterval(timerInterval);
|
||||
}
|
||||
|
||||
timerInterval = setInterval(() => {
|
||||
timeLeft--;
|
||||
|
||||
// update number
|
||||
textEl.textContent = timeLeft;
|
||||
|
||||
// 🔥 recompute progress EVERY tick
|
||||
const progress = (duration - timeLeft) / duration;
|
||||
|
||||
// update circle
|
||||
const offset = circumference * progress;
|
||||
circle.style.strokeDashoffset = -offset;
|
||||
|
||||
// color interpolation
|
||||
if (progress < 0.5) {
|
||||
circle.style.stroke = lerpColor(startColor, middleColor, progress * 2);
|
||||
} else {
|
||||
circle.style.stroke = lerpColor(middleColor, endColor, (progress - 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})`;
|
||||
}
|
||||
Reference in New Issue
Block a user