HTML DOM 快速導覽 - window 物件的方法 clearInterval()

window.clearInterval() 取消 setInterval() 設定的間隔時間重複動作。



clearInterval() 雖然是 window 物件的方法,在多數瀏覽器中也可單獨使用,也就是直接呼叫 clearInterval() ,不需要寫 window.clearInterval() 。


clearInterval() 需要一個參數
window.clearInterval(id);


id 為 setInterval() 的回傳值,舉例如下
var intervalID;

function run() {
    intervalID = window.setInterval(textColor, 2000);
}

function stop() {
    window.clearInterval(intervalID);
}

function textColor() {
    var t = document.getElementById("demo");
    t.style.color = randomColor(); 
}

function randomColor() {
    var c1 = (Math.random() * 1000) % 256;
    var c2 = (Math.random() * 1000) % 256;
    var c3 = (Math.random() * 1000) % 256;
    c1 = hex(Math.floor(c1));
    c2 = hex(Math.floor(c2));
    c3 = hex(Math.floor(c3));
    return "#" + c1 + c2 + c3;
}

function hex(n) {
    var result = "";
    var temp, count;
    while (n > 16) {
        count = 1;
        while (n > exp(16, count)) {
            count += 1;
        }
        count -= 1;
        temp = n / exp(16, count);
        temp = Math.floor(temp);
        result += hexLetter(temp);
        n -= exp(16, count) * temp;
    }
    if (n == 16) {
        result += "1";
        n -= 16;
    }
    result += hexLetter(n);
    
    return result;
}

function hexLetter(n) {
    if (n >= 16 || n < 0) {
        return "";
    }
    else {
        switch (n) {
            case 10:
                return "A";
            case 11:
                return "B";
            case 12:
                return "C";
            case 13:
                return "D";
            case 14:
                return "E";
            case 15:
                return "F";
            default:
                return "" + n;
        }
    }
}

function exp(x, y) {
    var result = 1;
    while (y > 0) {
        result *= x;
        y -= 1;
    }
    
    return result;
}


/* 《程式語言教學誌》的範例程式
     http://pydoing.blogspot.com/
     檔名:window048.js
     功能:示範 JavaScript 程式 
     作者:張凱慶
     時間:西元 2011 年 8 月 */


這裡設計 stop() 函數呼叫 clearInterval()
function stop() {
    window.clearInterval(intervalID);
}


我們以的 HTML 文件載入
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM DEMO</title>
<script src="window048.js" type="text/javascript"></script>
</head>
<body>
<input type="button" value="RUN" onclick="run();">
<input type="button" value="STOP" onclick="stop();">
<div id="demo" style="font-size:x-large;">There is no spoon.</div>
</body>
</html>

<!-- 《程式語言教學誌》的範例程式
     http://pydoing.blogspot.com/
     檔名:window048.html
     功能:示範 JavaScript 程式 
     作者:張凱慶
     時間:西元 2011 年 8 月 -->


瀏覽器 (broswer) 開啟後,點擊 RUN 文字就會每隔兩秒自動變換隨機顏色,再次點擊 STOP 就會停止變換隨機顏色




中英文術語對照
瀏覽器broswer


您可以繼續參考
window 物件


相關目錄
HTML DOM 快速導覽
JavaScript 教材
首頁


參考資料
https://developer.mozilla.org/en/DOM/window.back

沒有留言: