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

JS implementation of obtaining time and setting countdown code sharing

小云云
Release: 2018-02-28 11:50:29
Original
1990 people have browsed it

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template