BOM-Timing Events

 

BOM提供有關時間觸發的方法

 

一、setTimeout(function, milliseconds)

<!DOCTYPE html>
<html>
<body>
    <p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>
    <button id="myButton">Try it</button>

    <script>
        document.getElementById("myButton").addEventListener("click", mySetTimeout);
        function mySetTimeout() {
            setTimeout(myFunction, 3000);
        }
        function myFunction() {
            alert('Hello');
        }
    </script>
</body>
</html>

此範例為,當按下按紐經過三秒後,觸發myFunction方法一次。

 

二、setInterval(function, milliseconds)

<!DOCTYPE html>
<html>
<body>
    <p id="myP">Click "Try it". per 1 seconds, and the page will display time .</p>
    <button id="myButton">Try it</button>

    <script>
        document.getElementById("myButton").addEventListener("click", mySetTimeout);
        function mySetTimeout() {
            setInterval(myFunction, 1000);
        }
        function myFunction() {
            document.getElementById("myP").innerHTML = new Date();
        }
    </script>
</body>
</html>

此範例為,當按下按紐後,每秒會觸發myFunction方法一次。

 

三、window.clearTimeout(timeoutVariable)

此方法用來清除時間變數,直白的說,就是中斷方法,防止時間觸發被執行。

 

對setTimeout方法的清除範例

<!DOCTYPE html>
<html>
<body>
    <p>Click "Try it". Wait 1 seconds, and the page will alert "Hello".</p>
    <button id="myButton">Try it</button>
    <button id="buttonStop">Stop it</button>

    <script>
        var timerVariable;

        document.getElementById("myButton").addEventListener("click", mySetTimeout);
        function mySetTimeout() {
            timerVariable = setTimeout(myFunction, 1000);
        }
        function myFunction() {
            alert('Hello');
        }

        document.getElementById("buttonStop").addEventListener("click", myStop);
        function myStop() {
            window.clearTimeout(timerVariable);
        }
    </script>
</body>
</html>

 

對setInterval方法的清除範例

<!DOCTYPE html>
<html>
<body>
    <p id="myP">Click "Try it". per 1 seconds, and the page will display time .</p>
    <button id="myButton">Try it</button>
    <button id="buttonStop">Stop it</button>

    <script>
        var timerVariable;

        document.getElementById("myButton").addEventListener("click", mySetTimeout);
        function mySetTimeout() {
            timerVariable = setInterval(myFunction, 1000);
        }
        function myFunction() {
            document.getElementById("myP").innerHTML = new Date();
        }

        document.getElementById("buttonStop").addEventListener("click", myStop);
        function myStop() {
            window.clearTimeout(timerVariable);
        }
    </script>
</body>
</html>

 

參考資料:

window.requestAnimationFrame()

最佳化 JavaScript 執行