같은 시간 간격으로 코드를 실행하고 싶을 때 사용
setInterval(sayHello, 5000);
JavaScript에 있는 Date Object를 이용해 날짜, 시간을 쉽게 표현할 수 있다.
const clock = document.querySelector("h2#clock");
function getClock() {
const date = new Date();
clock.innerText = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}
getClock();
setInterval(getClock, 1000);
JavaScript의 padStart 함수를 이용해서 자릿수를 쉽게 맞출 수 있다.
function getClock() {
const date = new Date();
clock.innerText = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
clock.innerText = `${hours}:${minutes}:${seconds}`;
}
getClock();
const clockTitle = document.querySelector(".js-clock");
const christmasEve = new Date("12/25/2022");
function getClock() {
const now = new Date();
const diffTime = Math.floor((christmasEve.getTime() - now.getTime()) / 1000);
const diffSecs = diffTime % 60;
const diffMins = Math.floor(diffTime / 60) % 60;
const diffHours = Math.floor(diffTime / 60 / 60) % 24;
const diffDays = Math.floor(diffTime / 60 / 60 / 24);
clockTitle.innerText = `${diffDays}d ${diffHours}h ${diffMins}m ${diffSecs}s`;
}
getClock();
setInterval(getClock, 1000);