[13-1] 스크립트 태그의 위치
[13-2] JS로 HTML, CSS 조작
[13-3] 반복문이란?
[13-4] 반복문 활용
[13-5] interval 적용
[13-6] 함수의 인자와 매개변수
[13-7] 브라우저의 저장소
반복문
은 반복적인 코드의 양을 획기적으로 압축하고 반복적인 일의 수행을 효율적으로 처리 할 수 있도록 도와준다.
for(최초식; 조건식; 증감문){ ---------> 반복을 수행할 코드 }
최초식 while( 조건식 ){ ---------> 반복을 수행할 코드 증감식 }
const arr = [1, 2, 3, 4, 5] for(let i of arr) { console.log(el) }
const obj = { name : "otter", gender : "male" } for(let key in obj) { console.log(key) }
setInterval()
함수는 반복 함수지정한 시간
마다 반복해서 실행해 준다.고유의 id 값
을 반환아이디를 소괄호 안에 넣고 실행해주면
반복 실행하던 interval이 종료됩니다.외부의 데이터를 받아온 후 가공
, 혹은 로직을 수행
하는 것도 가능하다.매개변수를 함께 정의해줬다면 함수를 호출하는 과정에서 전달인자 를 건네줄 수 있다.
전달인자 1, 2가 매개변수인 one과 two에 담기게 된다.
이때, 전달인자를 담아주는 순서 에 의해서 매개변수에 담길 값 이 정해진다.
웹 브라우저에서 어떠한 로직에 활용되는 데이터를 유지시키고자 한다면, 해당 데이터를 저장할 공간이 필요하다.
웹 브라우저는 Web Storage
라고 하는 저장소를 제공 하는데, seesionStorage
와 localStorage
를 활용할 수 있다.
세션
은 사용자가 페이지에 접속하는 순간부터 접속이 끊어지는 순간
까지 를 이야기한다.비휘발성 메모리
이기 때문에 저장된 데이터가 브라우저, pc를 종료하더라도 그대로 남아있게 된다.
localStorage는 window.localStorage로 접근할 수 있다.
데이터를 저장할 때는 localStorage에 내장되어 있는 setItem이라는 메서드 를 사용하면 된다.
localStorage.setItem('data-key', 'data-value')
첫번째 인자로 key 를, 두번째 인자로 value, 저장할 데이터를 담아주면 된다.
localStorage에 존재하는 데이터를 꺼내올 수 있다.
localStorage.getItem(’data-key’)
const messageContainer = document.querySelector('#d-day-message');
const container = document.querySelector('#d-day-container');
const savedDate = localStorage.getItem('saved-date');
const intervalIdArr = [];
container.style.display = 'none';
messageContainer.innerHTML = '<h3>D-Day를 입력해 주세요.</h3>';
const dateFormMaker = function () {
const inputYear = document.querySelector("#target-year-input").value;
const inputMonth = document.querySelector("#target-month-input").value;
const inputDate = document.querySelector("#target-date-input").value;
const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;
return dateFormat;
};
const counterMaker = function (date) {
if (date !== savedDate) {
localStorage.setItem('saved-date', date);
}
const messageContainer = document.querySelector('#d-day-message');
messageContainer.textContent = 'D-Day를 입력해 주세요.';
const targetDateInput = dateFormMaker();
const nowDate = new Date();
const targetDate = new Date(date).setHours(0, 0, 0, 0);
const remaining = (targetDate - nowDate) / 1000;
if (remaining <= 0) {
container.style.display = 'none';
messageContainer.innerHTML = '<h3>타이머가 종료되었습니다.</h3>';
messageContainer.style.display = 'flex';
setClearInterval();
return;
} else if (isNaN(remaining)) {
container.style.display = 'none';
messageContainer.innerHTML = '<h3>유효한 시간대가 아닙니다.</h3>';
messageContainer.style.display = 'flex';
setClearInterval();
return;
}
const remainingObj = {
remainingDate: Math.floor(remaining / 3600 / 24),
remainingHours: Math.floor(remaining / 3600) % 24,
remainingMin: Math.floor(remaining / 60) % 60,
remainingSec: Math.floor(remaining) % 60
}
const format = function (time) {
if (time < 10) {
return '0' + time;
} else {
return time;
}
}
const documentObj = {
days: document.getElementById('days'),
hours: document.getElementById('hours'),
min: document.getElementById('min'),
sec: document.getElementById('sec')
};
const timeKeys = Object.keys(remainingObj);
const docKeys = Object.keys(documentObj);
for (let i = 0; i < timeKeys.length; i = i + 1) {
const remainingTime = format(remainingObj[timeKeys[i]]);
documentObj[docKeys[i]].textContent = remainingTime;
};
};
const starter = function (targetDateInput) {
if (!targetDateInput) {
targetDateInput = dateFormMaker();
}
container.style.display = 'flex';
messageContainer.style.display = 'none';
setClearInterval();
counterMaker(targetDateInput);
const intervalId = setInterval(() => { counterMaker(targetDateInput); }, 1000);
intervalIdArr.push(intervalId)
};
const setClearInterval = function () {
localStorage.removeItem('saved-date');
for (let i = 0; i < intervalIdArr.length; i++) {
clearInterval(intervalIdArr[i]);
}
}
const resetTimer = function () {
container.style.display = 'none';
messageContainer.innerHTML = '<h3>D-Day를 입력해 주세요.</h3>';
messageContainer.style.display = 'flex';
setClearInterval()
}
if (savedDate) {
starter(savedDate);
} else {
container.style.display = 'none';
messageContainer.innerHTML = '<h3>D-Day를 입력해 주세요.</h3>';
}