防止定时器叠加

  • 防止定时器叠加的方法就是在开启定时器之前先清除定时器,再开启
  • 定时器叠加:开启定时器之后每次触发事件事件都会重复执行,表现为事件执行的频率加快
<!DOCTYPE html>
<html>
     <head>
           <meta charset="UTF-8">
           <title></title>
           <style>
                 #box{
                  width:150px;
                  height:150px;
                  background-color:red;
               }
           </style>
     </head>
     <body>
         <div id="box"></div>
         <script>
               var box=document.getElementById("box");
               var change=0;
               var timer=null;
             //监听盒子的鼠标移入事件
     box.onmouseover=function(){
             //清除定时器
    clearInterval(timer);
             //开启定时器
            timer=setInterInterval(function(){
                 change+=1;
                consoel.log(change);
        },1000);    
          }
         </script>
     </body>
</html>

猜你喜欢

转载自www.cnblogs.com/zhang-jiao/p/9690387.html
今日推荐