The countdown:
The first thing is to know the current time, and the target time, and work out the time difference between them
function timeCount(){ var target=new Date('2019/8/14 19:58:00').getTime(), now=new Date().getTime(), time=target-now; If (time <= 0){clearInterval(timer); clearInterval(timer); // This line stops the timer when the countdown reaches 00 hours 00 minutes 00 seconds. return }Copy the code
Get the number of integer hours in these milliseconds, then round up the minutes in the remaining milliseconds, and then round up the seconds in the remaining milliseconds
var hours=parseInt(time/(1000*60*60)); // Number of milliseconds in an hour time=time-hours*1000*60*60; var minutes=parseInt(time/(1000*60)); // The number of milliseconds in a minute time=time-minutes*1000*60; var seconds=parseInt(time/1000); // The number of milliseconds per second time=time-seconds*1000;Copy the code
Then, if you end up at the top, you will get the desired result, but in order to look neat, we add zero in front of the time, not to mention really beautiful.
If (hours<10){// If (hours<10){// If (hours<10){// If (hours<10){ The same goes for the following. hours='0'+hours; } if(minutes<10){ minutes='0'+minutes; } if(seconds<10){ seconds='0'+seconds; }Copy the code
This step is pretty straightforward, define a variable, concatenate the resulting hours and seconds with strings, and we’ll get what we want.
Var STR = '${hours} ${minutes} ${seconds}'; document.getElementById('time1').innerHTML =str;Copy the code
}
This step is to use the timer to make the whole program run
var timer=setInterval(()=>{ timeCount(); },1000)//1000 represents 1sCopy the code