js realizes countdown effect accurate to milliseconds

  • 2021-07-09 06:46:07
  • OfStack

In this paper, we share the countdown effect accurate to milliseconds for your reference. The specific contents are as follows


<!DOCTYPE html>
<html>

 <head>
 <meta charset="UTF-8">
 <meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
 <title></title>
 <style>
  div{
  width: 100%;
  height: 50px;
  margin-bottom: 5px;
  background: yellowgreen;
  }
 </style>
 </head>

 <body>
 
 <h2> A countdown of milliseconds </h2>
 <div id="timer1"></div>
 <div id="timer2"></div>
 <div id="timer3"></div>
 <div id="timer4"></div>
 <script>
  var addTimer = function(){
  var list = [],
   interval;
   
  return function(id,timeStamp){
   if(!interval){
   interval = setInterval(go,1);
   }
   list.push({ele:document.getElementById(id),time:timeStamp});
  }
  
  function go() { 
   for (var i = 0; i < list.length; i++) { 
   list[i].ele.innerHTML = changeTimeStamp(list[i].time); 
   if (!list[i].time) 
    list.splice(i--, 1); 
   } 
  }

  // Incoming unix Timestamp, get countdown 
  function changeTimeStamp(timeStamp){
   var distancetime = new Date(timeStamp*1000).getTime() - new Date().getTime();
   if(distancetime > 0){ 
                // If greater than 0. Explain that the deadline has not been reached   
   var ms = Math.floor(distancetime%1000);
   var sec = Math.floor(distancetime/1000%60);
   var min = Math.floor(distancetime/1000/60%60);
   var hour =Math.floor(distancetime/1000/60/60%24);
   
   if(ms<100){
    ms = "0"+ ms;
   }
   if(sec<10){
    sec = "0"+ sec;
   }
   if(min<10){
    min = "0"+ min;
   }
   if(hour<10){
    hour = "0"+ hour;
   }
   
   return hour + ":" +min + ":" +sec + ":" +ms;
   }else{
                // If not, it is already the deadline 
   return " Deadline! "
   } 
  }  
  }();
  
  addTimer("timer1",1451923200);//1 Month 5 Day 00 Point, unix Time stamp yourself to Baidu 1 Under, there is 
  addTimer("timer2",1451926800);//1 Month 5 Day 01 Point 
  addTimer("timer3",1451930400);//1 Month 5 Day 02 Point 
  addTimer("timer4",1452020400);//1 Month 6 Day 03 Point 

 </script>
 
 </body>

</html>

For more articles about countdown, please see the special topic: "Countdown Function"


Related articles: