Real time display of time left for an event in days, hours, minutes and secondsWe 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 ).
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().
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
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.
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.
Here is the code
If you are not able to copy the above code then check this text file with code.