In an active business, we often see the page in the clock, giving the user the start and status of the activity.
There are digital displays, with analog quartz clocks. Consensus, the logic behind it is the same, but the difference between the way the foreground is displayed.
Let's implement a digital display of the electronic clock.
Divided into display days and time division seconds two cases; We declare here that the DOM element ID of the page used to display the Times is J_count, var domcount = document.getElementById (' J_count ');
There's an X-day from the start of the event
-
Gets the point in time when the page was entered. That is the start of timing.
Because the clocks of the user machine are somewhat different from one another. In a more stringent time-critical scenario, it is recommended to issue Ajax or JSONP requests to the server when the page is opened to get the clock on the servers. This way, no matter how much time the user terminal machine is different, you can ensure that each user requests to and the server's clock is synchronous (we declare that the server returned timestamp is Servernow, in milliseconds).
var now = new date (number (servernow)) | | new date (), //date object nowtime = now . gettime (); //number of milliseconds
Calculates the initial days difference (we declare the end date to be endtime, in milliseconds)
-Nowtime, = deltatime/, Math. Ceil (deltasenconds/* *distance activity starts with '+' days //Redraw DOM content
Atomic Clocks Walk the table and execute callbacks at the end of time
Ver interval=SetInterval (function () {//repeats Deltaseconds--in 1 seconds; //beep deltadays = math. Ceil (deltasenconds/(60*60*24)); domcount.innerhtml = "+ deltadays + day //redraw dom content if (!deltadays) { Clearinterval (interval); Location. reload (); //suppose our callback is to refresh the page}}, 1000);
The full page (HTML&JS) code is:
"' javascript<! DOCTYPE html>
At the end of the activity there is an X-x.-X-SecondThe algorithm is the same, the only difference is to calculate the time division seconds three variables
```javascriptvar interval = setInterval(function(){ var hours = Math.floor(deltaSenconds/(60*60)), //时 minutes = Math.floor((deltaSenconds - hours*60*60)/60), //分 seconds = deltaSenconds - hours*60*60 - minutes*60; //秒 deltaSenconds--; if(hours < 10){ hours = ‘0‘ + hours; } if(minutes < 10){ minutes = ‘0‘ + minutes; } if(seconds < 10){ seconds = ‘0‘ + seconds; } $domCount.innerHTML = ‘距离活动结束还有‘+ hours +‘时-‘+ minutes +‘分-‘+ seconds +‘秒‘; if(!deltaSenconds){ clearInterval(interval); location.reload(); //假设到点后我们的回调是刷新一下页面 }},1000);```
The full page (HTML&JS) code is:
"' javascript<! DOCTYPE html>
End
JS implementation of Countdown