티스토리 뷰

setInterval 함수를 사용하여 스크립트 내에서 특정 함수를 반복 호출할 수 있다.

setInterval함수는 다음과 같이 사용한다.

setInterval(함수명, 밀리초 시간)

즉, 다음과 같이 코드를 작성하여 현재 시간을 계속 업데이트하여 디지털 시계를 구현할 수 있다.

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>현재 시각은?</title>
  <style>
    #current {
      margin-top:20px;
    }
    .display {
      font-size:26px;
      font-weight:bold;
      color:blue;
      text-align:center;
    }
  </style>
</head>
<body>
	<div id = "current" class = "display"></div>
	<script>
		setInterval(displayNow, 1000); //setInterval(함수명, 밀리초 시간) 
			
		function displayNow(){
			var date = new Date();
			document.querySelector("#current").innerHTML = date.toLocaleTimeString();
		}
	</script>
</body>
</html>

Comments