0

私はこのコードをstackoverflowで見つけましたが、タイマーがどのように正確に最初の時間を自動的に開始するかをまだ自問自答しています。

しかし、私はこれにコメントしていることに気付きました:

 //Optionally, activate each timer:
 //restart(i)();

タイマーの自動開始を防ぎます。

それは自動実行機能である可能性があり、そうである場合。この場合、ボタンがまだクリックされていなくても、自動実行可能な機能は常に自動起動しますか?

また、関数内で自動実行される関数が他にもあることがわかりました。誰かがこれがどのように機能するかを説明できますか。

<!DOCTYPE html PUBLIC>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>


<script src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>

</head>

<body>


<input type="submit" name="clear" value="Stop Timer" />
<input type="submit" name="reset" value="Restart Timer" />
<span id="count0">0</span>
<input type="submit" name="increment" value="Increment" />
<br />
<input type="submit" name="clear" value="Stop Timer" />
<input type="submit" name="reset" value="Restart Timer" />
<span id="count1">0</span>
<input type="submit" name="increment" value="Increment" />

<br />
<input type="submit" name="clear" value="Stop Timer" />
<input type="submit" name="reset" value="Restart Timer" />
<span id="count2">0</span>
<input type="submit" name="increment" value="Increment" />

<br />
<input type="submit" name="clear" value="Stop Timer" />
<input type="submit" name="reset" value="Restart Timer" />
<span id="count3">0</span>
<input type="submit" name="increment" value="Increment" />

<br />
<input type="submit" name="clear" value="Stop Timer" />
<input type="submit" name="reset" value="Restart Timer" />
<span id="count4">0</span>
<input type="submit" name="increment" value="Increment" />

<script>




    (function(){ //Anonymous function, to not leak variables to the global scope
        var defaultSpeed = 3000; //Used when missing
        var timerSpeed = [500, 1000, 2000, 4000, 8000];

        var intervals = [];



        function increase(i){
            return function(){
                var elem = $("#count"+i);
                elem.text(parseInt(elem.text()) + 1);
            }
        }
        function clear(i){
            return function(){
                clearInterval(intervals[i]);
            }
        }
        function restart(i){ //Start AND restart
            return function(){
                clear(i)();
                increase(i)();
                intervals[i] = setInterval(increase(i), timerSpeed[i]||defaultSpeed);
            }
        }




        // Manual increment
        $('input[name=increment]').each(function(i){
            $(this).click(function(){
                restart(i)();
                increase(i)();
            });
        });

        // Clear timer on "Clear"
        $('input[name=clear]').each(function(i) {
            $(this).click(clear(i));
        });

        // Restart timer on "Restart"
        $('input[name=reset]').each(function(i) {
            $(this).click(restart(i));

            //Optionally, activate each timer:
            restart(i)();
        });


    })();






</script>
</body>
</html>
4

1 に答える 1