Вы не поняли петли в JavaScript. Циклы выполняются немедленно, а не один l oop в секунду. Вы должны иметь некоторое время. Вы можете использовать window.setTimeout
или window.setInterval
, но я предпочитаю requestAnimationFrame
вместе с некоторыми Date()
вычислениями, как здесь
console.clear();
function startTimer(element, seconds) {
"use strict";
var start = new Date();
var now, diff, eta;
function getMinutes() {
return Math.max(0, Math.ceil((eta - eta % 60) / 60))
}
function getSeconds() {
return Math.max(0, Math.ceil(eta % 60))
}
function format(x) {
return (''+x).padStart(2, '0');
}
function draw() {
element.innerHTML = format(getMinutes()) + ':' + format(getSeconds())
}
function finished() {
element.classList.add('finished')
}
function update() {
now = new Date();
diff = (now.getTime() - start.getTime()) / 1000
eta = seconds - diff;
draw()
if (eta > 0) {
window.requestAnimationFrame(update)
} else {
finished()
}
}
update()
}
startTimer(document.getElementById("timer"), 720);
#timer {
font-size: 72px;
font-weight: bold;
font-family: sans-serif;
color: white;
}
#timer.finished {
color: red;
}
html, body {
height: 100%;
}
body {
background-color: #000;
display: -webkit-box;
display: flex;
-webkit-box-align: center;
align-items: center;
-webkit-box-pack: center;
justify-content: center;
}
<div id="timer"></div>