How to make a countdown timer in asp.net web application(C#)?

Prem picture Prem · Nov 11, 2010 · Viewed 14.2k times · Source

I am creating timed online test in C# asp.net. I have created it using the local machine time. But in the case of Database disconnection or system hang, The countdown timer must start from the time at which the machine has hanged or unexpected database disconnectivity. For example the user is answering the Questions for 10 mins and unexpectedly system hanged. After recovery the countdown must start from 10 mins. Can anyone please help me with coding in C#?

I have used the following code, But its not useful in the above scenario.

int totalTime = (Convert.ToInt32(ViewState["totaltime"])) * 60;

DateTime startTime = (DateTime)ViewState["startTime"];
TimeSpan elaspedTime = DateTime.Now.Subtract(startTime);
Literal1.Text = elaspedTime.Hours.ToString() + "h" + ":" + elaspedTime.Minutes.ToString() + 
    "m" + ":" + elaspedTime.Seconds.ToString() + "s";

int finish = Convert.ToInt32(elaspedTime.TotalSeconds);

int remaingsec = (totalTime - finish);
TimeSpan remainingtime = TimeSpan.FromSeconds(remaingsec);
string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s",
                    remainingtime.Hours,
                    remainingtime.Minutes,
                    remainingtime.Seconds,
                    remainingtime.Milliseconds);

LIteral2.Text =  answer;
if (totalTime == finish)
{
     lnkFinish_Click(sender, e);
     Response.Redirect(@"~/Error.aspx");
}

Answer

Dr. Rajesh Rolen picture Dr. Rajesh Rolen · Nov 11, 2010

i think its better to take a field in table and set total time for question in it and update that field on every 15/30 seconds (as per your required frequency) and on every update substract the value 15/30 second from total time. and do this till the field has value > 0.

for this you can take help of timer (javascript timer) and ajax. to send request to server to update that field.

with ajax i think its better to create a webservice (which will update value of that field) and call it using ajax on basis of javascript timer. well you can also use ajax timer.

javascript timer reference:

http://dotnetacademy.blogspot.com/2010/09/timer-in-javascript.html