Javascript, Jquery로 실시간 시간 구하기


본 예제를 통해 배울 수 있는 학습 부분
     1. Jquery를 항상 최신버전으로 유지
     2. Javascript, Jquery를 이용한 페이지 로드 순서
     3. setInterval()로 지정한 시간만큼 반복 
     4. new Date()로 실시간 시간 구하기
     5. String.slice()로 문자열 자르기
     6. clearInterval()로 반복정지


<%--jquery를 항상 최신버전으로 사용할 수 있다.--%> 
<script  src="http://code.jquery.com/jquery-latest.min.js"></script> 
<script> 
    var date; 

    
//document.ready -> window.ready -> window.onload 
    //window.onload = function () {}; (페이지 로드가 끝난 다음에 실행)  
    //$(window).ready(function () {}); (페이지 내의 이미지나 리소스 로드 후 실행) 
    //$(document).ready(function(){}); (페이지 DOM이 그려지면(태그등이 그려지고) 실행) 

    $(document).ready(function () { 
        startDate(); 
    }); 

    function startDate() { 
        date = setInterval(function () { 
            var dateString = "Today's date is: "; 

            var newDate = new Date(); 

            //String.slice(-2) : 문자열을 뒤에서 2자리만 출력한다. (문자열 자르기) 
            dateString += newDate.getFullYear() + "/"; 
            dateString += ("0" + (newDate.getMonth() + 1)).slice(-2) + "/"; //월은 0부터 시작하므로 +1을 해줘야 한다. 
            dateString += ("0" + newDate.getDate()).slice(-2) + " "; 
            dateString += ("0" + newDate.getHours()).slice(-2) + ":"; 
            dateString += ("0" + newDate.getMinutes()).slice(-2) + ":"; 
            dateString += ("0" + newDate.getSeconds()).slice(-2);
          
  //document.write(dateString); 문서에 바로 그릴 수 있다. 
            $("#date").text(dateString); 
        }, 1000); 
    } 

    function stopDate() { 
        clearInterval(date); 
    } 

    
//setInterval(function(){},1000); 해당 시간마다 (1초마다) 반복 된다. 
    //setTimeout(function(){},1000); 해당 시간뒤 (1초뒤) 한번만 실행된다. 
    //clearInterval(); 반복정지 

</script> 

<!DOCTYPE html> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
    <title></title> 
</head> 
<body> 
    <div> 
        <div id="date"></div> 
        <button onclick="startDate()">시작</button> 
        <button onclick="stopDate()">정지</button> 
    </div> 
</body> 
</html>


+ Recent posts