Home  >  Article  >  Web Front-end  >  JS implementation of obtaining time and setting countdown code sharing

JS implementation of obtaining time and setting countdown code sharing

小云云
小云云Original
2018-02-28 11:50:291954browse

This article mainly shares with you the JS implementation of obtaining time and setting countdown code, hoping to help everyone.

Just take notes and record them, mainly using Date and setInterval
The setting of the first countdown:

<script type="text/javascript">
    var timeBox = document.querySelector("#time");    function countdown(){
      var nowTime = new Date();      var targetTime = new Date("2018/2/27 15:44:15");      var spanTime = targetTime-nowTime;      if(spanTime <=0){
        timeBox.innerHTML="立即抢购";
        clearInterval(countdown);
      }else{        var hours = Math.floor(spanTime/(1000*60*60));
      spanTime-=hours*60*60*1000;      var minute = Math.floor(spanTime/(1000*60));
      spanTime-=minute*60*1000;      var second = Math.floor(spanTime/1000);
      hours<10 ? hours=&#39;0&#39;+hours : hours;
      minute<10 ? minute=&#39;0&#39;+minute : minute;
      second<10 ? second=&#39;0&#39;+second : second;
      timeBox.innerHTML=hours+&#39;:&#39;+minute+&#39;:&#39;+second;
      }

    }    var timer = window.setInterval(countdown,1000);  </script>

The second one , display the current date:

<script type="text/javascript">
    var timeBox = document.querySelector("#time");    function countdown(){
      var date = new Date();      var hours = date.getHours();      var minute = date.getMinutes();      var second = date.getSeconds();
      hours =checkTime(hours);
      minute =checkTime(minute);
      second =checkTime(second);
      timeBox.innerHTML = hours+&#39;:&#39;+minute+&#39;:&#39;+second;
    }    // 检测时间数字是否小于10,在小于10的数字前加一个‘0’
    function checkTime(i){
      i<10 ? i="0"+i :i;      return i;
    }    var timer = window.setInterval(countdown,1000);  </script>

Related recommendations:

JS method of obtaining time function and extension function

JS obtain Time method_javascript skills

js anti-refresh countdown code js countdown code

The above is the detailed content of JS implementation of obtaining time and setting countdown code sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn