프로그래밍/자바스크립트
Javascript : 일,시분초 카운드다운 만들기 (Countdown Days Hours Minutes Seconds)
재우니
2022. 9. 21. 12:27
Javascript : 일,시분초 카운드다운 만들기 (Countdown Days Hours Minutes Seconds)
var countDownDate = new Date("2022-09-21 11:20:00").getTime();
function timePart(val, text, color = "black") {
return `<h1 class="timer" style="color:${color};">${val}<div>${text}</div></h1>`
}
var x = setInterval(function () {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
let res = timePart(days, 'days') + timePart(hours, 'hours') + timePart(minutes, 'Mins');// + timePart(seconds, 'Seconds', 'red');
document.getElementById("timer").innerHTML = res
console.log(distance);
if (distance < 0) {
clearInterval(x);
let res = timePart(0, 'days') + timePart(0, 'hours') + timePart(0, 'Mins'); // + timePart(0, 'Seconds', 'red');
document.getElementById("timer").innerHTML = res
//document.getElementById("timer").innerHTML = "EXPIRED";
}
}, 1000);
초 단위까지 카운팅을 보고자 한다면.. timePart(0, 'Seconds', 'red') 를 코드 사용하시면 됩니다.
let res = timePart(days, 'days') + timePart(hours, 'hours') + timePart(minutes, 'Mins') + timePart(seconds, 'Seconds', 'red');
document.getElementById("timer").innerHTML = res
원본 출처
https://stackoverflow.com/questions/55937350/making-a-javascript-countdown-timer