5초간 카운트다운 만들어봅니다.
index.html
<div class="timer">
<div class="second"></div>
</div>
style.css
.second {
display: inline-block;
font-size: 24px;
}
script.js
window.onload = function() {
const secondElement = document.querySelector('.second');
const godlTime = new Date().getTime() + 5 * 1000;
update();
function update() {
const currentTime = new Date().getTime();
const leftTime = godlTime - currentTime;
secondElement.innerText = (leftTime / 1000).toFixed(2);
if (leftTime <= 0) {
secondElement.innerText = '5초가 지났습니다.';
return;
}
requestAnimationFrame(update);
}
};