JS:カウントダウンで止まる

JavaScript
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
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>タイマーによる数値カウント</title>
    <script>
        var count;          // カウント変数
        var counter = null;
         
        /*
         * 数値をカウントして表示する関数
         */
        function showCount(){
            // 数値を表示
            counter.innerHTML = count;
 
            // 0で止まる
            if(count <= 0){
                return;
            }
             
            // 数値をインクリメント
            count--;
 
            // 1秒後に再起呼び出し
            setTimeout(showCount, 1000);
        }
         
        /*
         * 起動時の処理
         */
        window.addEventListener("load", function(){
            // 表示位置のDOMを取得
            counter = document.getElementById("counter");
 
            // カウンタ値を0からカウント開始
            count = 3;
            showCount();
        });
    </script>
</head>
<body>
    <h1>タイマーによる数値カウント</h1>
    <p id="counter"></p>
</body>
</html>

コメント