js倒计时简单实现代码

倒计时: 

1.设置一个有效的结束日期 

2.计算剩余时间 

3.将时间转换成可用的格式 

4.输出时钟数据作为一个可重用的对象 

5.在页面上显示时钟,并在它到达0时停止

html

<div id="clock">
  <span id="days"></span>天
  <span id="hours"></span>时

  <span id="minutes"></span>分

  <span id="seconds"></span>秒

</div>


js代码 

<script><br>/*计算剩余时间*/
  function getTimeReamin(endtime){
   //剩余的秒数
    var remainSec=(Date.parse(endtime)-Date.parse(new Date()))/1000;
    var days=Math.floor(remainSec/(3600*24));
    var hours=Math.floor(remainSec/3600%24);
    var minutes=Math.floor(remainSec/60%60);
    var seconds=Math.floor(remainSec%60);
    return{"remainSec":remainSec,
     "days":days,
     "hours":hours,
     "minutes":minutes,
     "seconds":seconds
    }
  } 
var endtime="2016/10/10";
var clock=document.getElementById("clock");
//设置定时器
var timeid=setInterval(function () {
  var t=getTimeReamin(endtime);
  //判断时间格式
  days= t.days>=0&& t.days<10?"0"+t.days:t.days;
  hours= t.hours>=0&& t.hours<10?"0"+t.hours:t.hours;
  minutes=t.minutes>=0&&t.minutes<10?"0"+t.minutes:t.minutes;
  seconds=t.seconds>=0&&t.seconds<10?"0"+t.seconds:t.seconds;
  //设置时间
  document.getElementById("days").innerText= days;
  document.getElementById("hours").innerText= hours;
  document.getElementById("minutes").innerText= minutes;
  document.getElementById("seconds").innerText=seconds;
  //清除定时器
  if(t.remainSec<=0){
    clearInterval(timeid);
  }
});
<script> 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。