JSFiddle - React, Tailwind, and code Playground
by Sergei Sokolov
HTML
<div class="container">
<div id="obj1"></div>
<div id="obj2"></div>
<div id="obj3"></div>
</div>
CSS
#obj1, #obj2, #obj3 {
float:left;width:50px; height:50px;
background:#383;
margin-right:7px;
color:white;
text-align:center;
padding-top:30px;
border-radius: 4px;
}
.finished{background-color:#c30 !important;}
.container{width:175px;margin:100px auto 0}
JavaScript
/**
* для вопроса https://toster.ru/q/545210
*/
const Clock = {
watch: [],
add: function(el, D) {
this.watch.push({
el: el,
D : D,
});
this.tick();
},
tick: function(){
const now = new Date().getTime();
for(let i = this.watch.length - 1; i>=0; i--) {
let w = this.watch[i];
let dt = w.D.getTime() - now;
w.el.innerText = Math.round(dt / 1000);
if( dt<=0 ) {
w.el.classList.add('finished');
this.watch.splice(i,1);
}
}
},
timer: null,
init: function() {
this.timer = window.setInterval(this.tick.bind(this), 1000);
}
};
Clock.init();
Clock.add(
document.getElementById('obj1'),
new Date( new Date().getTime() + 5e3)
);
Clock.add(
document.getElementById('obj2'),
new Date( new Date().getTime() + 7e3)
);
Clock.add(
document.getElementById('obj3'),
new Date( new Date().getTime() + 3e3)
);