Please Enable JavaScript!
Gon[ Enable JavaScript ]

반응형

"남은 시간을 화면에 표시하는 시계 만들기"를 구현하는 방법은 JavaScript를 사용하여 현재 시간과 목표 시간 간의 차이를 실시간으로 업데이트하고 이를 화면에 표시하는 것입니다. 이를 위해 타겟 시간과 현재 시간을 구하고 차이를 계산한 후 document.getElementById() 와 1초마다 setInterval() 함수를 이용해서 웹 페이지를 업데이트합니다.

 


 

 

1. HTML 구조

 

HTML 파일에서 "countdown.js" 스크립트를 로드하고 "timer"라는 요소를 사용하여 시간을 표시할 위치를 설정합니다.

 

<!DOCTYPE html>
<html>
<head>
         <title>Countdown Timer</title>
</head>
<body>
         <h1>남은 시간:</h1>
         <div id="timer"></div>
 
         <script src="countdown.js"></script>
</body>
</html>

 

 

2. 자바스크립트 소스 (countdown.js)

 

JavaScript 파일에서 displayRemainingTime 함수는 남은 시간을 계산하고 timer 요소에 결과를 업데이트하는 역할을 합니다. 목표 시간(targetDate)을 설정하고, 1초마다 setInterval을 사용하여 displayRemainingTime 함수를 호출하여 남은 시간을 업데이트합니다. 시간이 초과하면 "시간 초과"를 표시하고 업데이트를 중단합니다.

 

function displayRemainingTime(targetDate) {
	const now = new Date();
    const endDate = new Date(targetDate);
    const timeRemaining = endDate - now;
 
    if (timeRemaining <= 0) {
    	document.getElementById('timer').textContent = '시간 초과';
      	return;
    }
 
    const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);

    document.getElementById('timer').textContent 
    	= `${days}일 ${hours}시간 ${minutes}분 ${seconds}초`;
}
 
// 타겟 날짜 설정 (예: 2023년 12월 31일 23:59:59)
const targetDate = new Date('2023-12-31T23:59:59').getTime();
 
// 1초마다 업데이트
setInterval(() => {
         displayRemainingTime(targetDate);
}, 1000);

 

 

setInterval() 함수는 아래를 참고하세요.

https://mainia.tistory.com/6953

 

자바스크립트 setInterval() 함수 사용하는 방법

setInterval() 는 JavaScript에서 특정 시간 간격으로 함수를 반복 실행하기 위해 사용되는 함수입니다. setInterval() 함수를 사용하여 주기적으로 작업을 수행하거나 반복 작업을 예약할 수 있습니다. 이

mainia.tistory.com

 

document.getElementById() 사용법은 아래 포스팅을 참고하세요.

https://mainia.tistory.com/6965

 

자바스크립트 document.getElementById() 함수 사용하기

document.getElementById() 함수는 JavaScript에서 사용되며, DOM (Document Object Model)을 조작하기 위해 주로 사용합니다. 함수는 특정 ID를 가진 웹 페이지의 요소를 선택하고 조작하기 위한 핵심 도구로, 웹

mainia.tistory.com

 

 

3. 출력 결과

 

목표 날짜(targetDate)까지의 남은 시간이 실시간으로 업데이트되며, 화면에 "남은 시간"이 표시됩니다. 목표 시간까지 남은 시간이 없거나 시간이 초과한 경우 "시간 초과"가 표시됩니다. 이 코드를 사용하면 웹 페이지에 남은 시간을 표시하는 실시간 시계를 만들 수 있습니다.


 

 

반응형
Posted by 녹두장군1
,