zoukankan      html  css  js  c++  java
  • 2016-06-02 定时器 倒计时

    1.未做封装的代码很是混乱

        <style>
            input{ 300px;height:20px;margin: 10px}
            #btn{ 150px;height: 30px;margin-left: 65px}
        </style>
    
        <script>
          window.onload=function(){
              var inputs = document.getElementsByTagName('input');
              var timer=null;
              var seconds=null;
              var currentDate=null;
              var str='';
              var targetDate = new Date(inputs[0].value);//目标时间 固定不变的
              inputs[2].onclick=function(){
                  clearInterval(timer);
                  timer =setInterval(function(){
                      if(seconds>=0){
                          currentDate =new Date();//当前时间
                          seconds = Math.floor((targetDate-currentDate)/1000);//毫秒转换成s
                          str=Math.floor(seconds/86400)+'天'+Math.floor(seconds%86400/3600)+'时'+Math.floor(seconds%86400%3600/60)+'分'+seconds%60+' 秒';
                          inputs[1].value=str;
                      }else{
                          clearInterval(timer);
                      }
    
                  },1000);
              }
          }
        </script>
    </head>
    <body>&nbsp;离:<input type="text" value="June 7,2016 00:00:00"><br>
    还剩下:<input type="text"><br>
    <input id="btn" type="button" value="开始倒计">
    </body>

    2.封装后的代码,更快更好

        <script>
          window.onload=function(){
              var inputs = document.getElementsByTagName('input');
              var timer=null;
              var delta=null;
              var currentDate=null;
              var str='';
              var targetDate = new Date(inputs[0].value);//目标时间 固定不变的
              inputs[2].onclick=function(){
                  firstGet();//否则页面出现卡顿,这个是上来就显示时间信息到input框中
    
                  clearInterval(timer);
                  timer =setInterval(firstGet,1000);
                  function firstGet(){
                      if(delta>=0){
                          currentDate =new Date();//当前时间
                          delta =targetDate-currentDate;
                          str=getDayHourMinSecondByMs(delta);
                          inputs[1].value=str;
                      }else{
                          clearInterval(timer);
                      }
                  }
    
              }
          }
            function getDayHourMinSecondByMs(ms){
               var  seconds = Math.floor(ms/1000);//毫秒转换成s
                return Math.floor(seconds/86400)+'天'+Math.floor(seconds%86400/3600)+'时'+Math.floor(seconds%86400%3600/60)+'分'+seconds%60+' 秒';
          }
        </script>
  • 相关阅读:
    Oracle存储过程和自定义函数笔记
    怎样将一个Long类型的数据转换成字节数组
    Java集合框架整理
    有了这些,java IO就不愁了
    java生成Excel文件,下载
    ajax使用
    java transient关键字
    Mysql乐观锁与悲观锁
    Spring(六)Spring执行流程
    Spring(五)AOP
  • 原文地址:https://www.cnblogs.com/bravolove/p/5554893.html
Copyright © 2011-2022 走看看