0

I am developing an web application where i need a count down timer. Im using asp.net

asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Label ID="lblHour" Text="" runat="server"></asp:Label>
        <asp:Label ID="lblMin" Text="" runat="server"></asp:Label>
        <asp:Label ID="lblSec" Text="" runat="server"></asp:Label>
        <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="timer_Tick">
        </asp:Timer>

    </ContentTemplate>


    </asp:UpdatePanel>

Code behind

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Session["time"] = DateTime.Now.AddSeconds(40);
    }


}

protected void timer_Tick(object sender, EventArgs e)
{
    TimeSpan time1 = new TimeSpan();
    time1 = (DateTime)Session["time"] - DateTime.Now;
    if (time1.Seconds <= 0)
    {
        lblSec.Text = "TimeOut!";
    }
    else
    {
        lblSec.Text = time1.Seconds.ToString();
    }


}

The problem i am having is, the timer wont decrement properly. It starts with 38, then goes to 35 then 32 and so on.

Is there a way to fix this problem?

1 Answer 1

1

I reckon the issue here is that when timer is triggered, the time it executes the code, it is little longer then one sec, 1 sec + some micro seconds, this is the cause of this output. Test this in your code.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["time"] = DateTime.Now.AddSeconds(40);
        }
    }

    protected void timer_Tick(object sender, EventArgs e)
    {
        var endTime = (DateTime) Session["time"];
        var endMin = ((DateTime)Session["time"]).Minute;
        var endSec = ((DateTime)Session["time"]).Second;
        var endMsec = ((DateTime)Session["time"]).Millisecond;
        var currentTime = DateTime.Now;
        var currentMin = currentTime.Minute;
        var currentSec = currentTime.Second;
        var currentMsec = currentTime.Millisecond;

        var time1 = endTime - currentTime;

        lblHour.Text = string.Format("End Sec - {0}:{1}:{2}", endMin, endSec, endMsec);
        lblMin.Text = string.Format("Current Sec - {0}:{1}:{2}", currentMin, currentSec, currentMsec);

        lblSec.Text = time1.Seconds <= 0 ? "TimeOut!" : time1.Seconds.ToString();
    }
Sign up to request clarification or add additional context in comments.

1 Comment

I placed timer outside the updatepanel and used trigger to call the timer function. It solved my problem. thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.