JavaScript之——定时器

定时器是window对象提供的方法。

1.设置定时器:

setTimeOut():只执行一次。用于在指定的毫秒数后调用函数或计算表达式,返回一个 ID(数字)。如:

setTimeout(function(){ alert("Hello"); }, 3000);

setInterval():周期性执行。按照指定的周期(以毫秒计)来调用函数或计算表达式,返回一个 ID(数字)。如:

setInterval('alert("Hello");', 3000);

2.清除定时器:

clearTimeOut():可取消由 setTimeout() 方法设置的定时操作。参数为 setTimeout() 返回的 ID 值。

clearInterval():可取消由 setInterval() 函数设定的定时执行操作。参数必须是由 setInterval() 返回的 ID 值。

示例:设置一个5秒的定时器,5秒后方块由黄变红。分别用setTimeOut()和setInterval()来实现相同的效果:

(1)setTimeOut()循环调用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script>
        function changeColor() {
            var timer=document.getElementById("timer");
            var time=parseInt(timer.value)-1;//timer.value获得的是字符串
            timer.value=time;
            if(time==0){
                var div=document.getElementById("test");
                div.style.background="red";
            }else {
                window.setTimeout("changeColor()",1000);
            }
        }
        window.setTimeout("changeColor()",1000);

    </script>
</head>

<body>
    <input type="button" value="5" id="timer">
    <div id="test" style="background: yellow;height: 300px;width: 300px">定时器</div>
</body>

</html>

(2)setInterval():

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script>
        function changeColor() {
            var timer=document.getElementById("timer");
            var time=parseInt(timer.value)-1;//timer.value获得的是字符串
            timer.value=time;
            if(time==0){
                var div=document.getElementById("test");
                div.style.background="red";
                window.clearInterval(clock);
            }
        }
          var clock=window.setInterval("changeColor()",1000);

    </script>
</head>

<body>
    <input type="button" value="5" id="timer">
    <div id="test" style="background: yellow;height: 300px;width: 300px">定时器</div>
</body>

</html>

运行效果:

                

猜你喜欢

转载自blog.csdn.net/linghuainian/article/details/81627961