Task description
Create a file under the same directory as the previous task, create it in the task0002_2.html
js
directory, task0002_2.js
and encode it to implement a countdown function.
- The interface first has a text input box, allowing to enter the date and year in a specific format
YYYY-MM-DD
;
- There is a button next to the input box, and when you click the button, the time difference between the 00:00:00 of the date entered by the current distance is calculated.
- Display in the page, distance yyyy mm month DD day and xx days xx hours xx minutes xx seconds
- Update the number displayed on the countdown every second
- If the time difference is 0, the countdown stops
At that time I thought it was quite simple, but when I did find a lot of not, mainly on the Date object unfamiliar;
Ideas:
The main is to obtain the input time and the current time difference, use this value to calculate the specific time difference, and then use settimeout every second to obtain the time difference between the page to refresh;
A picture of a Date object found on the Web:
- A common method of processing time and date in a Date object on an MDN;
Here I directly use the HTML5 input new attribute "date", click on the words directly display the calendar;
Convert the value of input to a Date object;
New Date () If no arguments are entered, the constructor for date creates a Date object based on the current time set by the system. Represents the current system time.
GetTime ()--Returns the number of milliseconds from 1970-1-1 00:00:00 UTC (Coordinated Universal Time) to that date, and returns a negative value for the time before 1970-1-1 00:00:00 UTC.
Date.now ()--Returns the number of milliseconds since 1970-1-1 00:00:00 UTC (Time Standard Time) to date.
In short, the first conversion to the same reference system and then the conversion of the value;
<body><input type= "Date" id= "Date2" ><button id= "Start" > Start </button><div class= " Count-down "></div></body><script>document.getElementById ("Start"). onclick=run; functionrun () {varEndtime=NewDate (document.getElementById ("Date2"). Value); varStarttime=Date.now ()varTime= (Endtime.gettime ()-starttime)/1000;//milliseconds change secondsvarDay=parseint (time/(60*60*24));//S Change day, below and so on;varHours=parseint (time/(60*60)%24);varMin=parseint (TIME/60%60);varSec=parseint (time%60); Document.getelementsbyclassname ("Count-down") [0].innerhtml= "<span>" + "distance setting time also:" +day+ "Days" +hours+ "hours" +min+ "minutes" +sec+ "seconds" + "</span>"; SetTimeout (Run,1000); if(time<=0) {cleartimeout (run); Document.getelementsbyclassname ("Count-down") [0].innerhtml= "Time Is up"; }}</script>
IFE JavaScript task0002-2 Little Exercise 2: Use of Date objects