I am attempting to design a blinking countdown timer that starts at 5 seconds and disappears when it reaches 0.
CSS:
.blinky {
transition: 1s opacity;
-moz-transition: 1s opacity;
-webkit-transition: 1s opacity;
}
HTML:
<div id="countdown" class="blinky">
JS:
const cdStart = 5;
countdown.innerHTML = cdStart;
countdown.style.opacity = 0;
for (var i = cdStart - 1; i > 0; i--) {
setTimeout(
(x) => {
countdownTime.innerHTML = x;
countdown.classList.remove('blinky');
countdown.style.opacity = 1;
countdown.classList.add('blinky');
countdown.style.opacity = 0;
},
1000 * (cdStart - i),
i
);
}
The goal is for the timer to display 5, fade out, show 4, fade out, display 3, fade out, show 2, fade out, and finally reveal 1 before disappearing. Each new number should instantly appear without fading back in. To achieve this, the "blinky" class is removed and added accordingly before adjusting the opacity.
However, the current setup only shows 5 and then stops functioning. Removing the opacity manipulation results in a functional countdown from 3 to 1. So I attempted to separate the class removal and addition events:
CSS:
.blinky {
transition: .9s opacity;
-moz-transition: .9s opacity;
-webkit-transition: .9s opacity;
}
JS:
const cdStart = 5;
countdownTime.innerHTML = cdStart;
countdown.style.opacity = 0;
for (var i = cdStart - 1; i > 0; i--) {
setTimeout(
(x) => {
countdownTime.innerHTML = x;
countdown.classList.remove('blinky');
countdown.style.opacity = '';
},
1000 * (cdStart - i),
i
);
setTimeout(() => {
countdown.classList.add('blinky');
countdown.style.opacity = 0;
}, 1000 * (cdStart - i) + 100);
}
With this attempt, I observed 5 fading out and then a delay before 1 appeared and faded away.
Is there a more reliable method to achieve the desired functionality here?