본문 바로가기

HTML/Javascript 기초

[Javascript] clearInterval 사용해보기

clearInterval은 setInterval로 실행된 함수를 초기화 시키는 함수이다.

<!DOCTYPE html>
<html lang="ko">

<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <!-- 경로 해결 문제 : <script type="text/javascript" src="../../js/jquery-3.5.1.min.js"></script> -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timer Example</title>
    <style>
        #output {
            border: 1px solid black;
            width: 30px;
            text-align: center;
            padding: 10px;
        }
    </style>

    <script type="text/javascript">

        var timerId;
        var $output;
        var count = 0;

        $(document).ready(function(){
            $output = $("#output");
        });

        function startTimer() {
            count=0;
            timerId = setInterval(addCount, 1000);
        }

        function stopTimer(){
            clearInterval(timerId);
        }

        function addCount(){
            count++;
            $output.text(count);
        }
    </script>
</head>

<body>
    <div id="output">
        0
    </div><br>
    <input type="button" value="시작" onclick="startTimer();">
    <input type="button" value="중지" onclick="stopTimer();">
    
</body>

</html>

 

 

728x90
반응형