[JavaScript] setInterval(), setTimeout()
포스트
취소

[JavaScript] setInterval(), setTimeout()

setInterval


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <button type="button" class="stopInterval">스탑</button>

    <script>
        window.onload = function() {

           var stop = setInterval(function() {  //1초 단위로 실행되는 Interval set
                console.log(1);
            }, 1000) 

            var stopInterval = document.querySelector(".stopInterval");
            stopInterval.onclick = function() { //정지버튼을 클릭했을때 Interval을 clear해줌
                clearInterval(stop) ;
            }
        }
    </script>
</body>
</html>

setTimeout


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <button type="button" class="stopTime">정지</button>

    <script>
        window.onload = function(){

        //    var stop = setTimeout(function(){
        //        alert("5초뒤 실행");
        //    }, 5000);

            var stop = setTimeout(test,5000);
            function test() {
                alert("5초뒤실행");
            }
            
            var stopTime = document.querySelector(".stopTime");
            stopTime.onclick = function(){
                clearTimeout(stop);
            }
        }
    </script>

</body>
</html>
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.