자바스크립트 Local Storage를 이용한 시계 애플리케이션 구현

JavaScript Logo

이번 포스트에서는 자바스크립트를 사용하여 시계 애플리케이션을 구현하는 방법을 알아보겠습니다. 또한, 시계의 상태를 Local Storage를 이용하여 유지할 수 있도록 개선할 것입니다. 시작하기 전에 자바스크립트와 HTML/CSS의 기본 지식이 필요합니다.

HTML 구조 설정하기

먼저, 시계를 표시할 HTML 구조를 설정해야 합니다. 이 예제에서는 다음과 같이 간단한 구조를 사용하겠습니다:

<!DOCTYPE html>
<html>
<head>
  <title>시계 애플리케이션</title>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <h1>시계 애플리케이션</h1>
  <div class="clock">
    <span id="hours">00</span>:
    <span id="minutes">00</span>:
    <span id="seconds">00</span>
  </div>

  <script src="script.js"></script>
</body>
</html>

CSS 스타일 지정하기

이제 CSS를 사용하여 시계의 스타일을 지정해보겠습니다. 이 예제에서는 다음과 같은 간단한 스타일을 적용하겠습니다:

body {
  padding: 20px;
  text-align: center;
}

h1 {
  font-size: 24px;
}

.clock {
  font-size: 48px;
  margin-top: 20px;
}

.clock span {
  padding: 5px;
  background-color: #efefef;
  border-radius: 5px;
}

JavaScript로 시계 구현하기

이제 자바스크립트를 사용하여 시계를 동적으로 표시하는 기능을 구현해보겠습니다. 아래의 코드를 script.js 파일에 추가합니다:

const hoursElement = document.getElementById('hours');
const minutesElement = document.getElementById('minutes');
const secondsElement = document.getElementById('seconds');

function updateTime() {
  const now = new Date();
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  hoursElement.textContent = hours;
  minutesElement.textContent = minutes;
  secondsElement.textContent = seconds;

  // 1초마다 시간 업데이트
  setTimeout(updateTime, 1000);
}

// 페이지 로드 시 시간 업데이트 시작
updateTime();

위의 코드는 현재 시간을 가져와서 시계에 표시하는 기능을 구현합니다. updateTime 함수는 1초마다 호출되어 시간을 업데이트합니다.

Local Storage를 이용한 상태 유지하기

이제 시계의 상태를 Local Storage를 이용하여 유지할 수 있도록 개선해보겠습니다. 아래의 코드를 script.js 파일에 추가합니다:

const hoursElement = document.getElementById('hours');
const minutesElement = document.getElementById('minutes');
const secondsElement = document.getElementById('seconds');

function updateTime() {
  const now = new Date();
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  hoursElement.textContent = hours;
  minutesElement.textContent = minutes;
  secondsElement.textContent = seconds;

  // 시간을 Local Storage에 저장
  localStorage.setItem('hours', hours);
  localStorage.setItem('minutes', minutes);
  localStorage.setItem('seconds', seconds);

  // 1초마다 시간 업데이트
  setTimeout(updateTime, 1000);
}

function restoreTime() {
  // Local Storage에서 시간을 가져와서 시계에 복원
  const hours = localStorage.getItem('hours');
  const minutes = localStorage.getItem('minutes');
  const seconds = localStorage.getItem('seconds');

  hoursElement.textContent = hours;
  minutesElement.textContent = minutes;
  secondsElement.textContent = seconds;
}

// 페이지 로드 시 상태 복원
window.addEventListener('load', restoreTime);

// 페이지 언로드 시 상태 저장
window.addEventListener('beforeunload', updateTime);

위의 코드는 updateTime 함수 안에서 localStorage 객체를 사용하여 시계의 상태를 계속 저장하고, restoreTime 함수를 사용하여 페이지 로드 시에 저장된 상태를 복원합니다. 또한, beforeunload 이벤트를 사용하여 페이지가 닫힐 때 상태를 저장합니다.

이제 위의 코드를 포함하는 script.js 파일을 웹 페이지에 추가하고, 웹 브라우저에서 애플리케이션을 열어 시계를 확인해보세요. 시계의 상태가 유지되는 것을 확인할 수 있습니다.

#javascript #localStorage #시계