JS ๋๋ฐ์ด ์นด์ดํธ ๊ณ์ฐ

์์ ๊ฐ์ด ๋ค์๋ ๋๊น์ง์ ์ผ ์๊ฐ ๋ถ ์ด๋ฅผ ๋ณด์ฌ์ฃผ๋ ํ๋ก๊ทธ๋จ์ ์ง๋๊ฒ์ด ๋ชฉ์ ์ ๋๋ค.
code
const clock = document.querySelector(".clock");
// 0d 00h 00m 00s
function getClock() {
const nowDate = new Date();
const nowYear = nowDate.getFullYear();
const dDate = new Date(`${nowYear + 1}/1/1`);
const dDay = dDate.getTime() - nowDate.getTime();
const day = Math.floor(dDay / (1000 * 60 * 60 * 24));
const hours = String(Math.floor((dDay % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))).padStart(2, "0");
const minutes = String(Math.floor((dDay % (1000 * 60 * 60)) / (1000 * 60))).padStart(2, "0");
const seconds = String(Math.floor((dDay % (1000 * 60)) / 1000)).padStart(2, "0");
clock.innerText = `${day}d ${hours}h ${minutes}m ${seconds}s`;
}
getClock();
setInterval(getClock, 1000);
์ฌ์ฉ ํจ์
new Date()
new Date("2021/9/1"); new Date("2021 9 1"); new Date("9/1/2021");
์๊ฐ์ ๋ณด๋ฅผ ๋ฐ์์ค๋ ํจ์.
์ธ์๊ฐ ์กด์ฌํ์ง์๋ค๋ฉด ํ์ฌ์๊ฐ์ ๊ธฐ์ค์ผ๋ก ๋ฐ์์ค๊ณ
์ธ์๋ฅผ ๋ ์ง ํ์์ผ๋ก ๋ฃ์ผ๋ฉด ์ง์ ๋ ๋ ์ง์ ์๊ฐ์ ๊ธฐ์ค์ผ๋ก ๋ฐ์์ค๊ฒ ๋ฉ๋๋ค.
์ธ์๋ฅผ ๋ฐ์์ฌ๊ฒฝ์ฐ๋ ์ง์ง ๋ค์ํ๊ฒ ๋ฃ์ด๋ ๊ฐ๋ฅ
Math.floor()
Math.floor(3.5) >> 3
์์์ ์ดํ๋ฅผ ๋ฒ๋ฆฌ๋ ํจ์
String.padStart(number, string)
const s = "1".padStart(2, "0"); >> "01" const s = "10".padStart(2, "0"); >> "10"
String์ ๊ธธ์ด๊ฐ number๋ณด๋ค ์งง๋ค๋ฉด String ์์ชฝ์ string ๋ฌธ์๋ฅผ ๋ถ์ฌ๋ฃ๋๋ค.
String์ ๊ธธ์ด๊ฐ ๋ ๊ธธ๋ค๋ฉด ๋ฌด์
function setInterval(function, number)
function sayHello() { console.log("HELLO") } setInterval(sayHello, 5000);
์ฃผ๊ธฐ์ ์ผ๋ก setInterval ํด๋น ํจ์๋ฅผ ์คํ์ํจ๋ค.
์์ ์ฝ๋๋ 5์ด๋ง๋ค console.log๋ก HELLO๋ผ๋ ๊ฐ์ ์ถ๋ ฅํด๋ผ ๋ผ๋ ๋ป์ด๋ค
clock.innerText
<h1 class="clock> test </h1> clock.innerText = "HELLO"; <h1 class="clock> HELLO </h1>
clock์ด๋ผ๋ ์ฝ๋์ text๋ถ๋ถ์ ๊ฑด๋๋ฆด ์ ์๋ ๋ฐฉ๋ฒ์ด๋ค.
ํด๋น ๋ด์ฉ์ ์ ๊ทผ์ ํด์ ๊ฐ์ ๊ฐ์ ธ์ฌ ์๋์๊ณ html์ ์์ ํ ์๋ ์๋ค.
date.getTime()
console.log(Date.getTime()) >> N ms
new Date๋ก ๊ฐ์ ธ์จ ๊ฐ์ ๊ธฐ์ค์ผ๋ก ๋ฐ๋ฆฌ์ด ๊ฐ์ผ๋ก ๋ด์ฉ์ ๊ฐ์ ธ์จ๋ค
1000ms == 1์ด