Friday, 2 March 2012

Real time changing Clock showing date and time in JavaScript

We can show a count down script displaying time left from an event. Say we are running a campaign which is going to end after two days. Here we will display a counter saying days , hours , minutes and seconds left for the event to happen or the campaign to end. This script uses the setTimeout function in the same way as it is used in displaying a changing clock script. Here this setTimeout script triggers another function in every 1000 mill seconds ( or in 1 sec ).

This script uses client side JavaScript to generate the count down clock. The initial value in number of seconds left for the countdown to end will be passed to the function. At the time of page loading the seconds left ( a numeric value ) is collected and based on this value the days , hours, minutes and seconds are calculated and displayed. So this script can be run by linking to a server side script like PHP or ASP and a powerful dynamic script can be developed. Let us not discuss the server side script part and we will only run the script with some numeric value for seconds which is collected at the time of page loads.

The script uses two functions. While the page loads we use the onload event of the body tag and pass a value to the function display_c().

<body onload=display_c(86501);>

Now this value of 86501 ( in Seconds ) is used to calculate the number of days, hours , minutes and seconds left for the event to happen.

Since this value we are going to use it again and again so we kept this in a global variable to use it inside and outside the functions like this

window.start = parseFloat(start);

WE have used windows object to store a variable in global scope to use throughout the page.

Now in each successive call to the function the value of this window.start is decreased by one after displaying the countdown value. The count down value changes after ever second and it gets the value after a short calculation.

window.start= window.start- 1;

The days left is calculated by taking the Math.floor value after dividing total time by 86400. This value of 86400 is the total number of seconds in a day ( 60 second x 60 minutes x 24 hours )

Similar way values of hours , minutes and seconds are calculated. A detail help is kept with comment lines inside the code.

Finally using a span id the count down is displayed.

No comments:

Post a Comment