首页 > 代码库 > 倒计时判断改良

倒计时判断改良

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>倒计时</title>
 6 </head>
 7 <body>
 8 
 9 </body>
10 <script type="text/javascript">
11      function timer(targetTime){
12         var date = new Date();
13         var dateTarget = new Date(targetTime);
14         var timeTarget = dateTarget.getTime();
15         var time = date.getTime();
16          if(timeTarget<time){
17              return "目标时间不能小于当前时间";
18          }
19         var time_difference = timeTarget-time;
20         var hour_point = time_difference/(1000*60*60);
21         var hour = Math.floor(hour_point);
22         var hour_difference =  hour_point-hour;
23         var minute_point =  hour_difference*60;
24         var minute = Math.floor(minute_point);
25         var minute_difference = minute_point - minute;
26         var second = Math.floor(minute_difference*60);
27          if(Number(hour)==0 && Number(minute)==0 && Number(second)==0){
28              return "时间到";
29          }
30         var timeStr = "还有 "+addZero(hour)+"小时 "+addZero(minute)+"分钟 "+addZero(second)+"秒 到时";
31         return timeStr;
32     };
33 
34      var timeFun = setInterval(function(){
35          var time_ = timer("2017/3/31 22:25:00");
36 
37          document.body.innerHTML = time_;
38 
39          if(time_ == "时间到" || time_=="目标时间不能小于当前时间"){
40              clearInterval(timeFun);
41          }
42 
43      },1000);
44 
45     function addZero(time){
46         return time<0?"0"+time:time;
47     }
48 
49 </script>
50 </html>

 

倒计时判断改良