Multiple Countdown Timer using jQuery.
In this blog, I will demonstrate how to set up a countdown timer based on dynamic data. Here, we are going to develop it in MVC framework with C#.
Prepare a dynamic date time list on the server side.
I have used a model named “TimerModel” as we assume that our dynamic timer data will come from the database.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace TimerDemo.Models
- {
- public class TimerModel
- {
- public string Name { get; set; }
- public string ReleaseDateTime { get; set; }
- }
- }
Create one controller and, for now, start preparing a dynamic list which should actually come from the database layer. Here, I have used a static datetime list; you can modify it to get appropriate results. After preparing the listset into "ViewBag.TimerList" take data from Controller to View.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using TimerDemo.Models;
-
- namespace TimerDemo.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- List<TimerModel> list = new List<TimerModel>();
-
- list.Add(new TimerModel
- {
- Name = "Display1",
- ReleaseDateTime = Convert.ToString(new DateTime(2018, 11, 25, 00, 30, 00))
- });
-
- list.Add(new TimerModel
- {
- Name = "Display2",
- ReleaseDateTime = Convert.ToString(new DateTime(2018, 11, 24, 23, 37, 00))
- });
-
- ViewBag.TimerList = list;
- return View();
- }
-
- public ActionResult About()
- {
- ViewBag.Message = "Your application description page.";
-
- return View();
- }
-
- public ActionResult Contact()
- {
- ViewBag.Message = "Your contact page.";
-
- return View();
- }
- }
- }
Clientside HTML setup
As I stored the list in "ViewBag.TimerList", grab it here on .cshtml page and make it dynamically bound for displaying the labels for the countdown.
- @using TimerDemo.Models.TimerModel
- @{
- ViewBag.Title = "Home Page";
- }
- <div class="jumbotron">
- <h1>ASP.NET</h1>
- <p class="lead">ASP.NET is a free web framework for building great Web
- sites and Web applications using HTML, CSS and JavaScript.</p>
- <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more
- »</a></p>
- </div>
- <div class="row">
- @if(ViewBag.TimerList != null)
- {
- for(TimerDemo.Models.TimerModel item in (List<TimerDemo.Models.TimerModel>)ViewBag.TimerList)
- {
- <p id="@item.Name"></p>
- }
- }
- </div>
ClientSide JavaScript function setup
Now, we need to handle the display update of labels every second by grabbing the Timer list through JavaScript. Follow the steps mentioned below and that’s it; your multiple dynamic time out counter is ready.
The ".cshtml" page has an "HTML" helper class which will help us to grab the dynamic list from the viewbag.
- <script type="text/javascript">
- var lstTimer = @Html.Raw(Json.Encode(ViewBag.TimerList));
- </script>
We just need to create a function which will calculate and give the difference between the current date time and TimerList's date and time. In this function, we will update the Countdown label too.
- function _SetTimerDisplay(objTime, label) {
-
- var now = new Date().getTime();
-
- var distance = (new Date(objTime.ReleaseDateTime).getTime()) - now;
-
- var days = Math.floor(distance / (1000 * 60 * 60 * 24));
- var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
- var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
- var seconds = Math.floor((distance % (1000 * 60)) / 1000);
-
- if (distance < 0) {
-
- objTime.Name = "EXPIRED";
- document.getElementById(label).innerHTML = "EXPIRED";
- }
- else {
-
- document.getElementById(label).innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
- }
- }
Now, we need to call the "_SetTimerDisplay()" JavaScript function for list item which we have grabbed from the ViewBag. So, in the following code, I have created the function "UpdateTimer()" which has foreach call "_SetTimerDisplay()" and updates the label for count down. It will check all the times that the countdown lists to see if all date time has expired or not. If expired, then it will stop calling this function. More clearance will be explained in the following steps.
-
- function UpdateTimer() {
- for (var i = 0; i < lstTimer.length; i++) {
- var iCount = 0;
- if (lstTimer[i].Name != 'EXPIRED') {
- _SetTimerDisplay(lstTimer[i], "Display" + (i + 1));
- iCount++;
- }
- }
- var vFound = lstTimer.find(function (element) {
- return (element.Name != "EXPIRED" ? true : false);
- });
- if (vFound == undefined) {
- clearInterval(x);
- }
- }
We need to setup interval calls for updating labels after every 1 second.
- var x = setInterval(function () {
- UpdateTimer();
- }, 1000);
Finally, you get the result as below. Here, I have put a snapshot so you can get different labels as per your given data in the controller.