1. 程式人生 > >JavaScript--利用setInterval或setTimeout實現背景顏色輪播

JavaScript--利用setInterval或setTimeout實現背景顏色輪播

Window屬性---暫停和定時器

暫停

var timeoutObj = setTimeout("執行程式",毫秒)

  1. setTimeout(引用,1000)
  2. setTimeout("執行程式",1000)

clearTimeout(timeoutObj)

定時器

var intervalObj = setInterval(("執行程式",毫秒)

  1. setInterval(引用,1000)
  2. setInterval("執行程式",1000)

clearInterval(intervalObj)

例題:

利用setTimeout實現背景顏色輪播

完整程式碼如下:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        div {
            width: 200px;
            height: 200px;
            border: 1px solid black;
            background-color: red;
        }
    </style>
</head>
<body>
    <div></div>
</body>
<script type="text/javascript">
    var divEle = document.getElementsByTagName("div")[0];
    func1();
    function func1() {
        divEle.style.backgroundColor = "red";
        setTimeout(func2, 1000);
    }
    function func2() {
        divEle.style.backgroundColor = "yellow";
        setTimeout(func3, 1000);
    }
    function func3() {
        divEle.style.backgroundColor = "blue";
        setTimeout(func1, 1000);
    }
</script>
</html>

利用setInterval實現背景顏色輪播

完整程式碼如下:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        div {
            width: 200px;
            height: 200px;
            border: 1px solid black;
            background-color: red;
        }
    </style>
</head>
<body>
    <div></div>
</body>
<script type="text/javascript">
    var divEle = document.getElementsByTagName("div")[0];
    var colors = ["red", "yellow", "blue"];
    var count = 0;
    setInterval(func, 1000);
    function func() {
        divEle.style.backgroundColor = colors[count++];
        if (count === 3) count = 0;
    }
</script>
</html>