Search code examples
asp.nettimercountdowncountdowntimer

ASP.NET countdown timer (hours, minutes, seconds)


I have to make a countdown timer where you choose the amount of seconds, minutes & hours for the timer to countdown. I found a video (https://youtu.be/zgxV7LaoGAk?t=930) where this guy explains how everything works, but his timer doesn't include hours.

This is the code for a countdown timer with only minutes & seconds:

var currentMinutes = (newTime.Length > 2) ?
    int.Parse(newTime.Substring(0, newTime.Length - 2)) :
    0;

var currentSeconds = (newTime.Length > 2) ?
    int.Parse(newTime.Substring(newTime.Length - 2)) :
    int.Parse(newTime);

Could anyone tell me how to write the code for a countdown timer with seconds, minutes AND hours (var currentHours ?)

var currentHours = ...


var currentMinutes = (newTime.Length > 2) ?
    int.Parse(newTime.Substring(0, newTime.Length - 2)) :
    0;

var currentSeconds = (newTime.Length > 2) ?
    int.Parse(newTime.Substring(newTime.Length - 2)) :
    int.Parse(newTime);

Solution

  • Ok, so how to do this?

    Well, we can do 100% server side code - great if you stuck - don't know JavaScript

    So, say we drop in 3 labels

    Drop in 3 text boxes.

    Drop in a timer control.

    Drop in 4 buttons - (see later how we use them).

    we have this:

        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    
        <div style="width:350px;padding:20px">
    
        <div style="margin:auto">
    
            <div style="float:left">
                <asp:Label ID="lblHours" runat="server" Text="Hours" Font-Size="Larger" ClientIDMode="Static"></asp:Label>
                <br />
                <asp:TextBox ID="txtHours" runat="server" Text="0" ClientIDMode="Static" CssClass="tbox"></asp:TextBox>
            </div>
    
            <div style="float:left;margin-left:20px">
                <asp:Label ID="lblMin" runat="server" Text="Minutes" Font-Size="Larger"></asp:Label>
                <br />
                <asp:TextBox ID="txtMin" runat="server" Text="0" CssClass="tbox" ClientIDMode="Static"></asp:TextBox>
            </div>
    
            <div style="float:left;margin-left:15px">
                <asp:Label ID="lblsec" runat="server" Text="Seconds" Font-Size="Larger"></asp:Label>
                <br />
                <asp:TextBox ID="txtSec" runat="server" BorderStyle="Solid" Text="5" CssClass="tbox" ClientIDMode="Static" ></asp:TextBox>
            </div>
    
            <div style="clear:both;height:15px"></div>
    
            <div style="margin:auto">
                <asp:Button ID="cmdStart" runat="server" Text="Start" />
                <asp:Button ID="cmdStop" runat="server" Text="Stop" style="margin-left:20px" />
    
                <asp:Button ID="cmdStartJS" runat="server" Text="Start JS" style="margin-left:20px"
                    OnClientClick="mystart();return false" />
                <asp:Button ID="cmdStopJS" runat="server" Text="Stop JS" style="margin-left:20px"
                    OnClientClick="mystop();return false"/>
                <br />
                <asp:Label ID="lblDone" runat="server" Text="" ClientIDMode="Static"></asp:Label>
            </div>
    
        </div>
        </div>
        <asp:Timer ID="Timer1" runat="server"></asp:Timer>
    

    And our code will look like this:

    Protected Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click
    
        ' take entered values - convert to time
        Dim MyTime As DateTime
        MyTime = TimeSerial(txtHours.Text, txtMin.Text, txtSec.Text)
    
        ' save time value
        ViewState("MyTime") = MyTime
    
        Timer1.Interval = 1000  ' upddate every one second
        Timer1.Enabled = True   ' start the timer.
        lblDone.Text = "Started"
    End Sub
    
    Protected Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    
        Dim myTime As DateTime = ViewState("MyTime")
    
        ' check if we are to stop
        If myTime <= TimeSerial(0, 0, 0) Then
            Timer1.Enabled = False      ' turn off timer
            ' do whatever for end of timer
            lblDone.Text = "Done!"
            Exit Sub
        End If
    
        Dim OneSecond As TimeSpan = TimeSpan.FromSeconds(1)
    
        myTime = myTime - OneSecond
        ' update text boxes
        txtHours.Text = myTime.Hour
        txtMin.Text = myTime.Minute
        txtSec.Text = myTime.Second
    
        ViewState("MyTime") = myTime
    
    End Sub
    
    Protected Sub cmdStop_Click(sender As Object, e As EventArgs) Handles cmdStop.Click
        Timer1.Enabled = False
    End Sub
    

    Output:

    enter image description here

    So the above is very similar to say desktop approach. (and like on desktop, we even dropped in that timer control).

    The downside of course is this means a post-back for each 1 second.

    But, we could surround the above markup with a update-panel - and it would be and look butter smooth.

    The 2nd way:

    100% Client side code.

    So, with the above page, lets write the JavaScript code for the "js buttons"

    We have this (I do assume this page has use of jQuery - but that's quite much assumed these days).

    <script>
    
        MyTime = new Date(0,0,0,0,0,0)
        TimeZero = new Date(0,0,0,0,0,0)
        MyTimer = 0
    
        tH = $("#txtHours")
        tM = $("#txtMin")
        tS = $("#txtSec")
    
        function mystart() {
    
            MyTime.setHours(tH.val())
            MyTime.setMinutes(tM.val())
            MyTime.setSeconds(tS.val())
    
            if (MyTime > TimeZero) {
                MyTimer = setInterval(mytic,1000)
                $("#lblDone").text("Start")
            }
        }
    
        function mytic() {
    
            MyTime.setSeconds(MyTime.getSeconds() - 1)
    
            tH.val(MyTime.getHours())
            tM.val(MyTime.getMinutes())
            tS.val(MyTime.getSeconds())
    
            if (MyTime <= TimeZero) {
                clearInterval(MyTimer)
                $("#lblDone").text("Done !!!")
            }
        }
    
        function mystop() {
                clearInterval(MyTimer)
        }
    </script>
    

    So both the JavaScript, or the server side code does quite much the same thing.

    The major difference you note is that the client side code? It never hits the server side, and thus looks quite a bit smoother.