Native JS Implementation Countdown

Source: Internet
Author: User

HTML code:

<div class= "box" > Distance from work and:<span>01:01:30</span></div>

CSS code:

*{
margin:0;
padding:0;
}
. box{
width:600px;
height:40px;
margin:30px Auto;
Text-align:center;
line-height:40px;
font-size:26px;
Font-weight:bold;
border:2px dashed darkred;
Background:lightcyan;
}
. Box span{
padding-left:10px;
Color:darkblue;
}
JS Code:
var span =
Document.getelementsbyclassname (' box ') [0].getelementsbytagname (' span ') [0];
var timer = window.setinterval (record,1000);
function record () {
var curdate = new Date ();//Gets the current time
var targetdate = new Date (' 2016/09/22 18:14:00 '); Target time, first converted to a time-formatted object to use the GetTime () method
var curDate1970 = Curdate.gettime (); Number of MS in current time distance 1970
var targetDate1970 = Targetdate.gettime (); Target distance of 1970 MS
var time = targetdate1970-curdate1970; Time difference
Conversion units convert time to h/m/s
Convert to hours first
var h = Math.floor (time/(1000*60*60)); Rounding down
Conversion minutes = The number of MS that is occupied by H hours is subtracted and then converted to minutes
var m = Math.floor ((time-h*60*60*1000)/(1000*60));
convert s = Subtract the number of MS that is occupied by hours and minutes, and then convert it to S
var s = Math.floor ((time-h*60*60*1000-m*60*1000)/1000);
if (H + m + s <= 0) {
Window.clearinterval (timer);
span.innerhtml = "00:00:00"
Return
}
span.innerhtml = Addzero (h) + ":" + Addzero (m) + ":" + Addzero (s);
}
function Addzero (n) {//Add a 0 before the number less than 10
return N < 10? ' 0 ' + n ';
}
Date.gettime (); The current date time is the number of milliseconds from 8 o'clock January 1, 1970.
Note: var date2 = new Date (' 2016/09/24 17:00:00 ');
Console.log (DATE2);
If a time-format string is added to the parentheses during new, the string is converted to a time object. Then you can use the getFullYear () method.
Date2.getfullyear ();

Native JS Implementation Countdown

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.