Creating a countdown timer for an ASP.NET web application using C#

As I work on developing a timed online test in C# ASP.NET, I encountered an issue with the countdown timer functionality. Currently, the timer is based on the local machine time, but if there is a database disconnection or system hang, it needs to resume from where it left off once the system is back up and running.

I have attempted to address this challenge using the following code snippet, however, it does not fully meet the requirements for resuming the timer after unexpected interruptions:


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

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

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

int remainingSec = (totalTime - finish);
TimeSpan remainingTime = TimeSpan.FromSeconds(remainingSec);
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 №1

In my view, the best approach is to implement a countdown using JavaScript (embedded) and passing your database data through JSON. In case of a disconnection from the database, send some data to JavaScript and initiate the countdown with appropriate control.

To get started, download the following JavaScript file and save it in your web application directory:

Then, you can use code similar to this example:

<script type="text/javascript">
        TargetDate = "12/25/207 12:01 AM";
        BackColor = "red";
        ForeColor = "white";
        CountActive = true;
        CountStepper = -1;
        LeadingZero = true;
        DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
        FinishMessage = "It is here!";
    </script>

Answer №2

In my opinion, it would be more efficient to create a dedicated field in the table to store the total time for each question. This field can be updated every 15/30 seconds based on the desired frequency, deducting 15/30 seconds from the total time with each update until the value reaches zero.

To implement this functionality, you could utilize a combination of a JavaScript timer and AJAX requests to update the field on the server side.

It may be beneficial to develop a web service specifically for updating the field value, which can be called using AJAX triggered by the JavaScript timer. Alternatively, an AJAX timer could also be used for this purpose.

For information on setting up a JavaScript timer, you can refer to the following resource:

Answer №3

Utilizing the Windows registry as a storage location for the counter is a viable option.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sign-Up with Node.js Form

I'm currently working on incorporating a registration form into my web application. After inserting the user-provided 'name' and 'email' into my MySQL database, I want distinct error messages to appear on the registration form if e ...

Utilizing the {{value}} parameter within the JavaScript block of the thinger.io HTML gadget

When creating an HTML widget with JavaScript code on the thinger.io Dashboard, you can easily include data from the "thing" by using {{value}} within HTML tags. However, incorporating this data into a JavaScript block poses a challenge. Example of a Pure ...

Which function is most suitable for verifying if the values from req.param are NaN and assigning a new value if they are found to be NaN?

Regarding the about page: I'm currently working on a react app that sends URL parameters to the backend server. The frontend URL looks something like this: maxprice=100000&minsqm=50&maxsqm=100&page=1, which are the user's filters for ...

What are some techniques for concealing the source of an iframe or embed tag with JavaScript, jQuery, or PHP?

Is there a way to conceal the src URL for a PDF file within an iframe or embed? I have tried various methods mentioned before, but none seem to be effective. <?php $url = $_GET['url']; ?> <embed id="renderedPrint" style=&q ...

Implementing JQuery to Traverse Through JSON Data in AJAX Response

I am currently working on an AJAX call that retrieves JSON data from a query: <script> function retrieveTrips(){ // Fetching the history of trips $.ajax({ url:'cfcs/mileagedata.cfc?method=getTrips&returnform ...

"Efficient Querying with MYSQL XDEVAPI Through Multiple OR (II) Requests

Currently, I am utilizing the XDEVAPI and attempting to incorporate the or(||) statement in JavaScript. However, it appears to malfunction after 1 or/(||) statements have been included. I need to fetch data from the database based on 5 distinct statuses: . ...

similar to a capture group but for a matched subdocument

In the database, there is a Chats collection with a participants subdocument structured as follows: { _id: '1', participants: [ { _id: 'A', seen: false }, { _id: 'B', seen: false } ], messages: [] } Each chat c ...

Is there a way to include a lockfile in a docker container as an optional step?

I am attempting to create a docker image that can optionally incorporate a yarn or npm lockfile during the build process. I want to include it explicitly, but also ensure that the build does not fail if the lockfile is missing. The goal is to respect dete ...

Angular UI-Router: Difficulty in Child State Accessing Parent Controller

I am currently using ui.router's nested views feature in my Angular application. Here is the relevant part of my .config: $urlRouterProvider.otherwise('/'); $stateProvider .state('home', { url: '/', templateUrl: ...

Creating labels dynamically with jQuery and HTML, then retrieving their text values through jQuery

During runtime, I am dynamically generating a label using jQuery with the following code: var value="Hello"; $("#ID_listOfTopics").append('<label id="ID_item">' + value + '</label><br /><hr />'); However, I&apo ...

Efficiently loading components in Angular using browserify with lazy loading

As I work on developing the architecture of a complex application with Angular, I have started with the angular-seed project which seems to be a solid starting point. However, one issue that concerns me is how Angular apps tend to load everything upfront b ...

Exploring the Process of Iterating through Data in Google Sheets to Set up a Trigger

My Google Apps Script Code is structured as follows: var key = "ID of the Sheet"; var key1 = "ID of the Sheet"; function createTriggers() { ScriptApp.newTrigger('filter') .forSpreadsheet(key) .onEdit() .create(); } funct ...

Why does the MEAN Stack continue to route using the '#' symbol in the URL?

Currently navigating the realm of back end development. Started off by following a guide on express from thinkster. In need of some clarification. Initially, I grasped that front-end and back-end routing serve different purposes. Front-end routing relates ...

How to send parameters to the Map method in Automapper

Currently, I am utilizing Automapper within a project and encountered the need to dynamically assign a value to a field in my destination object. Part of my configuration looks like this: cfg.CreateMap<Message, MessageDto>() // ... .ForMemb ...

The onchange tag fails to trigger my Javascript function when selected

Here is the code I have: JS: function updateLink() { var selType = document.getElementByID("Types"); var selLen = document.getElementByID("Length"); var selLoc = document.getElementByID ...

When a JSON stringified string contains a space-separated value, it can cause the data attribute to break

let dataObject = { "Cast_Code": "NA", "Mat_Code": "xxxx", "Pin_Num": "xxxx", "MatDetail": [ { "Batch_Number": "Patch PA", "Batch_Expiry": "No Expiry", "Batch_Quantity": "xxx", "Return_ ...

Creating hyperlinks in JSON response from a REST API with AngularJS - A guide!

I have a web application built with AngularJS, JS, JQ, and HTML5. This app can send various HTTP methods to the project's RESTful Web Service and receive responses in JSON format. The response is structured like this: When displayed in a <pre> ...

Log4net failing to capture errors from DLLs or website operations

I am facing issues with using log4net to log exceptions in a dll as nothing is being outputted. I have added the following code snippet to AssemblyInfo: [assembly: log4net.Config.XmlConfigurator(Watch = true)] I then initiated the logger on my class l ...

The web server is encountering an error with an unrecognized child element called "cors"

We recently completed a project with my team, but for some reason I am encountering an issue. Can anyone help me figure out why? https://i.sstatic.net/psQaU.png In my config.cs file, CORS has been enabled and the necessary NuGet packages have been instal ...

Can you explain the significance of `Component<Props>` in React Native?

Recently, I started a new react-native project and noticed a change in the component syntax. It now reads export default class WelcomeScreen extends Component<Props>, which is different from what it used to be, export default class WelcomeScreen exte ...