JS implementation Countdown-' How many days left '

Source: Internet
Author: User

First, start

This Tuesday to interview encountered a topic such as "please use JS to achieve the distance xx and left ... Days...... Hours...... Seconds ", at the time just thought to create a data to save how many days each month, and then to get the number of days subtraction on it.

Just to solve this problem, and did not think about it, now feel that this method is too cumbersome, and there is a leap year problem.

Now I'm going to re-write this method and use the time stamp to solve the problem.

Second, time stamp

What is a timestamp? The time stamp is actually now the time from GMT January 01, 1970 00:00 00 seconds (Beijing time January 01, 1970 08:00 00 seconds) up to now the total number of seconds.

  Note that there is a eight-hour error in time, so our direct new Date (2018-01-01) is actually the eight point of January 1, 2018, so we have to specify the timing.

Third, the realization

For example, we write a method to calculate how many days we have from 2018:

functionDatecount () {//get the time now        varDate =NewDate (); //the first day of 2018        varUntil =NewDate (' 2018-01-01 00:00:00 ')); //An implicit conversion occurs during calculation, and the valueof () method is called to convert to a timestamp form        varDays = (until-date)/1000/3600/24;//The following are simple mathematical calculations        varDay =Math.floor (days); varHours = (days-day) *24; varhour =Math.floor (hours); varminutes = (hours-hour) *60; varminute =Math.floor (minutes); varseconds = (Minutes-minute) *60; varSecond =Math.floor (seconds); varback = ' distance 2018 Left ' +day+ ' +hour+ ' hours ' +minute+ ' minutes ' +second+ ' seconds '; returnBack ; }

And then use the SetInterval () method to achieve real-time reciprocal

SetInterval (function() {        var text = datecount ();         // Show is a node        Show.innertext = text;},1000)

This achieves the reciprocal:

JS implementation Countdown-' How many days left '

Related Article

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.