Dynamic Multiple Time Countdown Display Using jQuery

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.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace TimerDemo.Models  
  7. {  
  8.     public class TimerModel  
  9.     {  
  10.         public string Name { getset; }  
  11.         public string ReleaseDateTime { getset; }  
  12.     }  
  13. }  

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.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using TimerDemo.Models;  
  7.   
  8. namespace TimerDemo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         public ActionResult Index()  
  13.         {  
  14.             List<TimerModel> list = new List<TimerModel>();  
  15.   
  16.             list.Add(new TimerModel  
  17.             {  
  18.                 Name = "Display1",  
  19.                 ReleaseDateTime = Convert.ToString(new DateTime(2018, 11, 25, 00, 30, 00))  
  20.             });  
  21.   
  22.             list.Add(new TimerModel  
  23.             {  
  24.                 Name = "Display2",  
  25.                 ReleaseDateTime = Convert.ToString(new DateTime(2018, 11, 24, 23, 37, 00))  
  26.             });  
  27.   
  28.             ViewBag.TimerList = list;  
  29.             return View();  
  30.         }  
  31.   
  32.         public ActionResult About()  
  33.         {  
  34.             ViewBag.Message = "Your application description page.";  
  35.   
  36.             return View();  
  37.         }  
  38.   
  39.         public ActionResult Contact()  
  40.         {  
  41.             ViewBag.Message = "Your contact page.";  
  42.   
  43.             return View();  
  44.         }  
  45.     }  
  46. }  
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.

  1. @using TimerDemo.Models.TimerModel
  2. @{  
  3.    ViewBag.Title = "Home Page";  
  4. }  
  5. <div class="jumbotron">  
  6.    <h1>ASP.NET</h1>  
  7.    <p class="lead">ASP.NET is a free web framework for building great Web   
  8.          sites and Web applications using HTML, CSS and JavaScript.</p>  
  9.    <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more   
  10.          »</a></p>  
  11. </div>  
  12. <div class="row">  
  13. @if(ViewBag.TimerList != null)
  14. {
  15.    for(TimerDemo.Models.TimerModel item in (List<TimerDemo.Models.TimerModel>)ViewBag.TimerList)
  16.    {
  17.       <p id="@item.Name"></p>  
  18.    }
  19. }  
  20. </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.

  1. <script type="text/javascript">    
  2.    var lstTimer = @Html.Raw(Json.Encode(ViewBag.TimerList));    
  3. </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.  

  1. function _SetTimerDisplay(objTime, label) {  
  2.             
  3.     var now = new Date().getTime();      
  4.     // Find the distance between now and the count down date      
  5.     var distance = (new Date(objTime.ReleaseDateTime).getTime()) - now;     
  6.     // Time calculations for days, hours, minutes and seconds      
  7.     var days = Math.floor(distance / (1000 * 60 * 60 * 24));      
  8.     var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));     
  9.     var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));      
  10.     var seconds = Math.floor((distance % (1000 * 60)) / 1000);      
  11.     // If the count down is over, write some text      
  12.     if (distance < 0) {      
  13.         //clearInterval(x);      
  14.         objTime.Name = "EXPIRED";      
  15.         document.getElementById(label).innerHTML = "EXPIRED";      
  16.     }      
  17.     else {     
  18.         // Output the result in an element with id="Display"      
  19.        document.getElementById(label).innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "
  20.      }      
  21. }  

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. 

  1. // Set the date we're counting down to    
  2. function UpdateTimer() {    
  3.     for (var i = 0; i < lstTimer.length; i++) {    
  4.         var iCount = 0;    
  5.         if (lstTimer[i].Name != 'EXPIRED') {    
  6.            _SetTimerDisplay(lstTimer[i], "Display" + (i + 1));    
  7.            iCount++;    
  8.         }    
  9.     }    
  10.     var vFound = lstTimer.find(function (element) {    
  11.         return (element.Name != "EXPIRED" ? true : false);    
  12.     });    
  13.     if (vFound == undefined) {    
  14.         clearInterval(x);    
  15.     }    
  16. }  
We need to setup interval calls for updating labels after every 1 second.
  1. var x = setInterval(function () {    
  2.     UpdateTimer();    
  3. }, 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.

Dynamic Multiple Time Countdown Display Using jQuery