四、定时器

四、定时器

  • 设置定时器:每隔一段时间,定时器(函数)会自动执行一次。

    • setInterval():

      • 第一个参数:函数

      • 第二个参数:间隔时间,单位是ms (1s=1000ms),省略不写

      • 调用对象:window,省略不写

      • 一般我们习惯将设置定时器赋值给timer变量。

  • 清除定时器:

    • clearInterval():

      • 参数:只需要书写要清除定时器的名称
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<div class="box" id="box">盒子</div>

<style>
    /* 清楚默认样式 */
    * {
        margin: 0;
        padding: 0;
    }
    .box {
        width: 200px;
        height: 200px;
        background-color:lightblue;
    }
</style>

<script>
    // 获取元素
    var oBox = document.getElementById("box");
    // 信号量
    var nowWidth = 200;
    // 每隔一段时间盒子变长
    var timer = setInterval(function(){
        // 信号量改变
        nowWidth += 20;
        // 信号量验证
        if(nowWidth >= 400){
            nowWidth = 400;
            // 超过400,清除定时器
            clearInterval(timer);
        }
        console.log(nowWidth);
        // 体现在元素身上
        oBox.style.width = nowWidth + "px";
    },1000);
    // 鼠标进入盒子,停止定时
    oBox.onmouseenter = function(){
        console.log(nowWidth);
        // 清除定时器
        clearInterval(timer);
    }
    // 鼠标离开盒子,继续变长
    oBox.onmouseleave = function(){
        // 设表先关
        // 重新开启定时器,需要先关闭之前的定时器,然后重新赋值
        clearInterval(timer);
        timer = setInterval(function () {
            // 信号量改变
            nowWidth += 20;
            // 信号量验证
            if (nowWidth >= 400) {
                nowWidth = 400;
                // 拉终停表,达到终点关闭定时器
                clearInterval(timer);
            }
            console.log(nowWidth);
            // 体现在元素身上
            oBox.style.width = nowWidth + "px";
        }, 1000);
    }
</script>

UAUEsP.png

点击查看

本文标题:四、定时器

文章作者:Mango

发布时间:2020年07月08日 - 22:10:14

最后更新:2020年07月08日 - 22:35:39

原始链接:https://mango185.github.io/post/38c658f2.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------