ASP.Net, C# and Javascript Count Down Timer
ASP.Net Code
While displaying a count down timer on your Web Page you need to do following things :
On the web page you need to add 7 controls.
In that one is HTML Text box which displays the count down time
<input type=”text” readonly =”true” size=”8″ id=”counter” style=”text-align:center; font-size:x-large; font-weight:bold; color:Red;” />
and rest of six are hidden fields in which three of them are HTML controls and other are ASP controls looks loke this
<input type=”hidden” size=”8″ id=”HidHours” value=”<%=HidH.Value%>“/>
<input type=”hidden” size=”8″ id=”HidMinutes” value=”<%=HidM.Value%>“/>
<input type=”hidden” size=”8″ id=”HidSeconds” value=”<%=HidS.Value%>“/>
<asp:HiddenField ID=”HidH” runat=”server” Value=”0″ />
<asp:HiddenField ID=”HidM” runat=”server” Value=”0″ />
<asp:HiddenField ID=”HidS” runat=”server” Value=”0″ />
Now you need to write the main JavaScript part which displays this count down time
<script>
var hours=document.getElementById(‘HidHours’).value;
var minutes=document.getElementById(‘HidMinutes’).value;
var seconds=document.getElementById(‘HidSeconds’).value;
function
display()
{
if (seconds<=0)
{
if ((hours==0)&&(minutes==0))
seconds=0;
else
{
seconds=60;
minutes-=1;
}
}
if (minutes<=0)
{
if ((hours<0)&&(minutes<0))
{
hours = minutes = seconds = 0;
}
else
{
if ((hours==0)&&(minutes==0))
hours=minutes=0;
if ((hours>0)&&(minutes<0))
{
minutes=59;
hours-=1;
}
}
}
if ((minutes<=-1)||(hours<=-1))
{
if (hours<=-1)
{
minutes=0;
hours+=1;
}
else
minutes-=1;
seconds=0;
minutes+=1;
}
else
if (seconds>0)
seconds-=1;
if (seconds <= 9 && seconds.toString().length < 2)
seconds = “0”+seconds;
if (minutes <= 9 && minutes.toString().length < 2)
minutes = “0”+minutes;
if (hours <= 9 && hours.toString().length < 2)
hours = “0”+hours;
document.getElementById(‘counter’).value=hours+“:”+minutes+“:”+seconds;
setTimeout(“display()”,1000);
}
display();
</script>
The Main Concept Over Here is the Time from where the count down begins that time you need to pass into ASP Hidden fields whose id are HidH, HidM and HidS which defines hours, minutes and seconds respectively. Now these values are passed to HTML Hidden Controls whose id are HidHours, HidMinutes and HidSeconds since the values of ASP controls value’s can not be passed directly to JavaScript code. We kept HTML controls as bridge between ASP controls Value’s and JavaScript. and Now Javascript function display() is called recursively until hours, minutes and seconds becomes zero. Once it is zero you can redirect to any page you want
C# Code
TimeSpan ts;
HidH.Value = Convert.ToString(ts.Hours);
HidM.Value = Convert.ToString(ts.Minutes);
HidS.Value = Convert.ToString(ts.Seconds);
click here : http://groups.google.co.in/group/dotnethelp2008/web/count-down-timer-asp-net-javascript-and-c?hl=en&msg=ns
It’s fantastic, Very help full to programmer….
keep doing like that….
yaa…. man
gr8..
Hi Ganesh,
I’m getting “Object Required” error in this line
var hours=document.getElementById(‘HidHours’).value;
Hi Gokul,
Please check whether you have a used a input type hidden field with ID as ‘HidHours’ ;
Ya I checked it still I’m getting error..
Thanks for ur reply
Ok… Can you Send me your Code to my Mail ID?? Let me Check and Reply you Back.
Ya sure tell me your mail id i’ll send it to you..
ganeshmohan99@gmail.com
Photometry says : I absolutely agree with this !
Gokul / photometry,
Place your javascript block below the body(i.e. at the end after the elements are declared) and you will see it working.
The document.getElementById(“…”) is not able to reach the element.
Hope this helps.
You are correct Pradeep… Yes That was the Error (Javascript should be placed inside the form tag)
Thanks a lott for the Post !!. But when ever there is a Postback in the Page the Value is again setting back to the Original Value, can you suggest any way to overcome this problem
Set Page Postback to false and Try it out. Hope it helps.
i got like this error
Control ‘HidH’ of type ‘HiddenField’ must be placed inside a form tag with runat=server.
Yes all your Controls should be placed in form tag of aspx page… otherwise that will not work
Hi Friends,
I used ur code in my web page that works fine, but when i raise a popup(Confirm) window then the timer stops, after clicking (ok or cancel) timer continues……… This should not happen for my requirment…..
According to me this is because both the timer, popup are javascript code…..
Any other Ideas???
Do help me as quick as possible
My mail Id is srinig29@gmail.com
seems to work for the time being. I’m going to build in leading zeros for the minutes and seconds so the timestamp doesn’t look weird like 12:8:2 for 12 hours 8 minutes and 2 seconds. Should look like 12:08:02 instead. Easy fix, will post the code when I’m done.
Meanwhile I don’t understand what this javascript is doing:
else
minutes-=1;
seconds=0;
minutes+=1;
Since all of the variables are independent in the javascript (unless you specifically link them in a given statement, which is not happening here), then what is the point of decrementing minutes and then incrementing them again? Was this just an oversight?
Thanks
————————-
To the guy who was worried about the value reverting to the start time each time you post back, why don’t you pass in a start time that changes based on your needs? I have passed in the following from the C# code:
//must count down from June 14 of the upcoming year
string yearEnd = “06-14-” + DateTime.Now.AddYears(1).Year.ToString();
//pass in the timespan between June 14 and today/now
TimeSpan ts = DateTime.Parse(yearEnd).Subtract(DateTime.Now);
Now every time you post back, the counter should take on the newly calculated timespan as defined in your c# code.
Here’s the snippet to get the time formatted like this 0:00:00
even when your minutes or seconds are <10
document.getElementById(‘counter’).value = days + ” Days ” + hours + “:” + (minutes < 10 ? “0” + minutes : minutes) + “:” + (seconds < 10 ? “0” + seconds : seconds);
—will generate a time like this: 9:08:03
instead of this: 9:8:3
Cheers
I did some testing, and this appears to work also. I’ve included DAYS as part of this function. You’ll have to pass in DAYS from c#; I did so using the same methods that Ganesh described above (asp.Hiddenfield, hidden input, etc).
———-
var days = document.getElementById(‘HidDays’).value;
var hours = document.getElementById(‘HidHours’).value;
var minutes = document.getElementById(‘HidMinutes’).value;
var seconds = document.getElementById(‘HidSeconds’).value;
function display() {
if (seconds <= 0) {
if ((hours == 0) && (minutes == 0))
seconds = 0;
else {
seconds = 60;
minutes -= 1;
}
}
if (minutes <= 0) {
if ((hours < 0) && (minutes 0) && (minutes 0))
{
days -= 1;
minutes = 59;
seconds = 59;
hours = 23;
}
if ((minutes <= -1) || (hours <= -1)) {
if (hours 0)
{
seconds -= 1;
}
}
if ((minutes == 0) && (hours == 0) && (seconds == 0) && (days == 0)) {
document.getElementById(‘counter’).value = “TIME EXPIRED.”;
}
else {
document.getElementById(‘counter’).value = days + ” Days ” + hours + “:” + (minutes < 10 ? “0” + minutes : minutes) + “:” + (seconds < 10 ? “0” + seconds : seconds);
}
setTimeout(“display()”, 1000);
}
display();
FYI the code I posted above appears to have been chopped as I posted it… missing some lines in the middle
Hi Jeremy,
Excellent Thought… I really like it. I did not test your code but I really appreciate your work.
Thanks a Lot… and since you asked “what is the point of decrementing minutes and then incrementing them again?” that is because as hour is decremented the minute is set back to ’59’ and been decremented, that depends on seconds until it is zero… here the second, hours and minutes depend upon each other…
My page does not show up anything just ablank text box. I am missign the linking of javascript function to page event, can u tell me how to do that
Hi Parul,
What Exactly you are doing? I need more information here…
if ((minutes == 0) && (hours == 0) && (seconds == 0) && (days == 0))
{
here i want to refresh the page.what can i do for this .can u help me plz
}
Thanks.,
It’s very Helped To Me.
It’s fantastic, Very help full to programmer…..
I did how to Reload the page.Now I got The Result
f ((minutes == 0) && (hours == 0) && (seconds == 0) && (days == 0))
{
location.reload(“Default.aspx”);
}
Thank You.
Cool Dude….
Thanks
hi
i need coding for a countdown timer for onlineexam application which should not get refreshed when the page got refreshed using asp.net & c#…………….
Hi Ganesh,
Thanks for your script.
I hv got an error and also a doubt.
In the code behind on page load, I hv placed the following code
TimeSpan ts;
HidH.Value = Convert.ToString(ts.Hours);
HidM.Value = Convert.ToString(ts.Minutes);
HidS.Value = Convert.ToString(ts.Seconds);
Its showing me the error saying that the variable is used before its assigned any value.
Can you pls help me.
I know I sound stupid for asking the basic question, but i am a newbie for asp.net .
Thanks a lot in advance.
Regards
Hi Swetha,
100% it will show error because you didn’t assign value to ts and calculating hours, minutes and seconds… instead of passing ts.Hours, ts.Minutes, ts.Seconds give some integer value and check out.
if you want to use ts then you need to assign some value to it like TimeSpan ts = new TimeSpan(2,30,30);
Regards
Ganesh
Hi Ganesh,
Thanks a lot for your reply. I managed to run the code.
But I have another problem now, 😦 Hope you dont mind solving.
When the countdown is finished, I need to show a confirm box to the user. If the user clicks ok, then I need to reset the timer. If clicked cancel, do nothing.
But I wasnt sure where I should put it.
If I put it in else loop, the confirm box keeps popping up everytime i click the ok button or cancel button.
If I place it outside the function, the confirm box does not shows up at all.
Can you pls help me over?
Thanks a lot for your help
Regards
Hi Ganesh,
Pls ignore the above message (I am not able to delete:( )
I have found the solution.
Now I hv another query which I really dont know how to do. 😦
Say for eg., if user clicks on the ok button on the confirm dialog, we reset the counter. If user clicks cancel then we dont reset the counter.
But if user doesnot do any action (like clicking any of the buttons,) then the clock should keep counting. and exit at the time we have provided.
How can we check whether the user clicked the button or not?
Thanks a lot for your help.
Regards
Hi swetha,
you have to alter the code.
var phours=document.getElementById(‘HidHours’).value;
var pminutes=document.getElementById(‘HidMinutes’).value;
var pseconds=document.getElementById(‘HidSeconds’).value;
hours = phours
minutes = pminutes
seconds = pseconds
And to display a confirm message
after display()
var check = confirm(“Can you do it?”);
if “check”is true then
hours = phours
minutes = pminutes
seconds = pseconds
else
//do nothing
BUT… when the confirm message is showed the countdown stops until u respond for that confirm message. it doesn’t mean that u don’t have solution for it… You have and u need to find it by urself since I don’t have time for these activities. Sorry I am very much busy in my current project.
Regards
Ganesh
hello ganesh, i am also in search of a javascript timer set from aspx code. And I tried ur code, but textbox is empty.
I cant figure out wher I went wrong. Hoping for you reply.
hi,
how can I tell where you are wrong without seeing your code?? 🙂 Can you send me your code to my mail ID… Let me have a look and tell you…
Thanks
Ganesh
i am also in search of a javascript timer set from aspx code. And I tried ur code, but textbox is empty.
I cant figure out wher I went wrong. Hoping for you reply.
jtharsh@gmail.com
hi this is sivanesan.b,your script is perfectly working fine,but i need retain the same time of countdown timer after the post back.now after the post back the timer start begining itself.is there any option to get back values from javascript to code behind.or else any ideas to retain the same time?????Thank you,Sivanesan.B
good
please send me full code
output is empty textbox
my id : jtharsh@gmail.com
Can you Send me your Code to my Mail ID ,bcoz the output is empty textbox
Ganesh Mohan,
i have create timer but i have one question how to maintain the timer in all pages
did you get the code to retain the timer in all the pages..?
please send me full code
output is empty textbox
my id : haquangtoan.it@gmail.com
Oh. i want to give them(countdown timer) into datalist, it’s mean: i want to display many countdown timer but it’s error. can u help me? and please for me a exam.
Hi i this is working fine!!, and i need to add one more logic here.
When page refresh the countdown reset again.
Plz solve this issue.
put the code of timer in master page