第四节 定时器

开启定时器:

  setInterval(函数名,时间间隔ms);  间隔型(每隔一段时间就会执行一次,无限地执行下去)

  setTimeout(函数名,时间延时ms)  延时型(开启系统后在“时间延时后”只执行一次)

停止定时器:  clearInterval():对应上面setInterval(name, time)  clearTimeout():对应上面setTimeout(name, time)  

  <script>
    window.onload=function(){
      var oBtn1=document.getElementById('btn1');
      var oBtn2=document.getElementById('btn2');
      var timer=null;

      oBtn1.onclick=function () {timer=setInterval(function () {alert('已开启timer定时器!');}, 5000);};
      oBtn2.onclick=function () {clearInterval(timer);alert('已关闭timer定时器!')};
    };
  </script>

  <button id="btn1">开启定时器</button>
  <button id="btn2">关闭定时器</button>

 应用举例:数码时钟

  获取系统时间:Date对象;    getHours、getMinutes、getSeconds

  显示系统时间:字符串连接,空位补零——如下面toDou(n)函数的定义;    

  设置图片路径:

    charAt()方法:用于解决兼容性问题,由于低版本浏览器的不兼容性,“str[i]”不会取出字符串中相应字符,所以我们要用“str.charAt(i)”任何浏览器都兼容  

  <script>
    function toDou(n){ //转换为两位字符串“051213”

      if (n < 10) {return '0'+n}
      else {return ''+n;}
    }
    window.onload=function(){
      var aImg=document.getElementsByTagName("img");
      function tick() {
        var oDate = new Date();  //Date对象
        var str = toDou(oDate.getHours()) + toDou(oDate.getMinutes()) + toDou(oDate.getSeconds());
        for (var i = 0; i < aImg.length; i++) {
          aImg[i].src = 'img/' + str.charAt(i) + '.png';
        }
      }
      //由于刚打开页面时,会有一秒“00:00:00”延迟才会显示正确系统时间,为了去掉延时,操作如下
      setInterval(tick, 1000);
      tick(); //原理就是,上面语句延时时,词句已调用函数
    };
  </script>

  <div id="div1">
    <img src="img/0.png"/>
    <img src="img/0.png"/>:
    <img src="img/0.png"/>
    <img src="img/0.png"/>:
    <img src="img/0.png"/>
    <img src="img/0.png"/>
  </div>

  <style>#div1{background: black;color: white;font-size: 100px;text-align: center;}</style>

 Date对象其他方法

  年getFullYear():获得系统年份

  月getMouth():获得系统月份,注意系统月份是从“0~11”

  日getDate():获得系统日期

  周getDay():0表示周日,1表示周一,依次类推……

延时提示框:  

  <style>
    div{float: left;margin: 10px;}
    #div1{width: 50px;height: 50px;background: red;}
    #div2{width: 250px;height: 250px;background: #ccc;display: none;}
  </style>
  <script>
    window.onload=function(){
      var oDiv1=document.getElementById('div1');
      var oDiv2=document.getElementById('div2');
      oDiv1.onmouseover=function () {
        clearTimeout(timer); //解决加入下半部分代码后div2闪现的问题
        oDiv2.style.display='block';
      };
      oDiv1.onmouseout=function () {
        timer=setTimeout(function () {
        oDiv2.style.display='none';
        }, 500);
      };
      //上述代码已经可以了,但是问题是移入div2后经过500msdiv2依然消失了
      oDiv2.onmouseover=function () {
        clearTimeout(timer);
      };
      oDiv2.onmouseout=function () {
        timer=setTimeout(function () {
          oDiv2.style.display='none';
        }, 500);
      };
    };
  </script>

  <div id="div1"></div>
  <div id="div2"></div> 

   原来的方法

    移入显示、移出隐藏

  移出延时隐藏

    一如下面的Div后,还是隐藏了

  简化代码:

    合并两个相同的 mouseover 和 mouseout    

    <script>
      window.onload=function(){
        var oDiv1=document.getElementById('div1');
        var oDiv2=document.getElementById('div2');
        var timer=null;
        oDiv2.onmouseover=oDiv1.onmouseover=function () {
          clearTimeout(timer);
          oDiv2.style.display='block';
        };
        oDiv2.onmouseout=oDiv1.onmouseout=function () {
          timer=setTimeout(function () {
            oDiv2.style.display='none';
          }, 500);
        };
      };
    </script>

无缝滚动(图片自动轮播)——基础

  物体运动基础

    让Div移动起来

    offsetLeft的作用:获取物体左边距,是一个数字,而且它可以综合考虑所有影响该物体位置的因素之后,计算出物体的“总左边距”,同理与此相对应还有offsetTop,以及offsetWidth、offsetHeight

    用定时器让物体连续移动

  效果原理

    让 ul 一直向左移动

  复制 li

    innerHTML 和 +=

    修改 ul 的 width

  滚动过界后,重设位置

    判断过界

无缝滚动——扩展

  改变滚动方向:修改speed、修改判断条件

  鼠标移入暂停:移入关闭定时器、移出重新开启定时器

代码展示:

<style>
    *{margin: 0;padding: 0;}
    #div1{
        width: 396px;
        height: 132px;
        background: red;
        position: relative;
        margin: 100px auto;
        overflow: hidden;
    }
    #div1 ul{
        position: absolute;
        left: 0;
        top: 0;
    }
    #div1 ul li{
        float: left;
        width: 99px;
        height: 132px;
        list-style:none;
    }
</style>
<script>
    window.onload=function(){
        var oDiv=document.getElementById('div1');
        var oUl=oDiv.getElementsByTagName('ul')[0];
        var aLi=oUl.getElementsByTagName('li');

        var speed = -2;     //控制轮播速度和方向,“+”表示向左走,“-”表示向右走,

        oUl.innerHTML=oUl.innerHTML+oUl.innerHTML;  //再复制一个<ul></ul>标签
        oUl.style.width=aLi[0].offsetWidth*aLi.length+'px';   //宽度加宽

        function move() {  //移动方法
            if (oUl.offsetLeft < -oUl.offsetWidth/2) {  
                oUl.style.left='0';
            }
            if (oUl.offsetLeft > 0) {
                oUl.style.left=-oUl.offsetWidth/2+'px';
            }
            oUl.style.left=oUl.offsetLeft+speed+'px';
        }

        var timer=setInterval(move, 30);  //用定时器让物体连续移动

        oDiv.onmouseover=function(){  //移入暂停
            clearInterval(timer);
        };
        oDiv.onmouseout=function () {  //移出播放
            timer=setInterval(move, 30);
        };

        document.getElementsByTagName('button')[0].onclick=function(){
            speed=-2;
        };
        document.getElementsByTagName('button')[1].onclick=function(){
            speed=2;
        };
    };
</script>

<body>
    <button>向左走</button>
    <button>向右走</button>
    <div id="div1">
        <ul>
            <li><img src="img/1.png"/></li>
            <li><img src="img/2.png"/></li>
            <li><img src="img/3.png"/></li>
            <li><img src="img/4.png"/></li>
        </ul>
    </div>
</body>
原文地址:https://www.cnblogs.com/han-bky/p/10072002.html