防止定时器重叠问题

描述

在浏览器中设置一个正方体盒子,当鼠标进入该盒子时,启动定时器。定时器完成在控制台一秒打印出一个数字的功能

图示

在这里插入图片描述

定时器重叠问题

但以上描述实现时存在一个问题。当鼠标多次进入该盒子时,控制台以远远小于一秒的速度打印出一个数字的功能。这就是定时器重叠问题。
原因 : 每当鼠标进入一次,就会生成一个定时器,而原来生成的定时器还是存在着(存在多个定时器实现功能),所以控制台打印数字的速度越来越快了

HTML+CSS

<style>
    #box  {
        width: 200px;
        height: 200px;
        margin: 20px auto;
        background-color: blue;
    }
</style>
<body>
    <div id="box"></div>
</body>

JS-----定时器重叠代码

<script>
    window.onload = function() {
        var count = 0;
        var box = document.getElementById("box");
        box.onmouseover = function() {
            setInterval(function(){
                console.log(count);
                count ++;
        },1000);
        };
        
    }
</script>

JS-----解决定时器重叠代码

以下代码就不会出现定时器重叠问题了

<script>
    window.onload = function() {
        var count = 0;
        var box = document.getElementById("box");
        var interval;		//定时器变量
        
        box.onmouseover = function() {
            //清除已存在的定时器
            clearInterval(interval)
            interval = setInterval(function(){
                console.log(count);
                count ++;
        },1000);
        };
        
    }
</script>
发布了51 篇原创文章 · 获赞 26 · 访问量 1833

猜你喜欢

转载自blog.csdn.net/qq_45473786/article/details/104929417