counter timer
an attempt at an efficient countdown timer that is based on setinterval. it will delete the timer when it is done.
by James Doyle
HTML
<ul id="timers">
<li id="001">10</li>
<li id="002">100</li>
<li id="003">300</li>
</ul>
CSS
ul {
width: 300px;
display: block;
}
li {
display: block;
height: 20px;
width: 100%;
background: green;
transition: all 0.5s ease;
}
li.done {
background: red;
width: 100% !important;
}
JavaScript
var timers = [{
id: '001',
start: 10,
duration: 10
}, {
id: '002',
start: 100,
duration: 100
}, {
id: '003',
start: 300,
duration: 300
}];
Array.prototype.remove = function (from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var counter = setInterval(timerChange, 1000);
function makeTimer(id, dur) {
timers.push({
id: id,
start: dur,
duration: dur
});
document.getElementById('timers').innerHTML += '<li id="' + id + '">' + dur + '</li>';
}
function timerChange() {
for (var i = 0; i < timers.length; i++) {
timers[i].duration -= 1;
var elem = document.getElementById(timers[i].id);
if (timers[i].duration >= 1) {
elem.innerText = timers[i].duration;
elem.style.width = Math.round((timers[i].duration / timers[i].start) * 100) + '%';
} else {
// remove the width attr
elem.setAttribute('style', '');
elem.innerText = 'done';
elem.className = 'done';
timers.remove(i);
}
}
}
makeTimer('005', 120);