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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<button type="button" id="pollStart">폴링시작</button>
<button type="button" id="pollStop">폴링정지</button>
<script src="lib/jQuery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
 
    var timeoutIds = [];
 
    function clearAllTimeout() {
        var ids = timeoutIds;
        for (var i=0; i<ids.length; i++) {
            window.clearTimeout(ids[i]);  // 전역에 저장된 타임아웃 아이디를 모두 제거
        }
        timeoutIds = [];             
    }
 
    var polling = function (code) { // 클로져 패턴
        return function() {
            clearAllTimeout(); // Timeout 초기화
            console.log(code); // 여기서 code 매개변수값을 사용하기 위해 클로저 패턴을 쓴것이다.
            var id = setTimeout(fn_closure, 2000);
 
            // 폴링시작 버튼을 연타할경우 인터벌이 점점 빨라지게 된다.     
            // 타임아웃 아이디를 배열에 저장하고, 버튼을 클릭할때 마다 초기화 해준다.
            timeoutIds.push(id); 
        }
    }
 
    var fn_closure = null; 
 
    $("#pollStart").click(function() {
        console.log("폴링시작");
        fn_closure = polling(Math.random()); // polling 함수의 반환값은 내부함수(클로져)이다.
        fn_closure();
    });
 
    $("#pollStop").click(function() {
        console.log("폴링중지");
        fn_closure = null; // 클로저 해제
    });
 
</script>
 
</body>
</html>


반응형
Posted by 힘없는염소