weixin_33744854 2011-03-17 08:46 采纳率: 0%
浏览 10

AJAX asp.net中的计时器问题

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条回答 默认 最新

  • weixin_33724046 2011-03-17 09:24
    关注

    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();
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制