2011-03-17 32 views
0

我正在開發一個Web應用程序,我需要一個倒數計時器。即時通訊使用asp.net在AJAX中的定時器問題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> 

代碼背後

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


} 

我有問題,計時器不會正確遞減。它從38開始,然後到35和32等等。

有沒有辦法解決這個問題?

回答

1

我認爲這裏的問題是,當定時器被觸發時,它執行代碼的時間稍長一秒,1秒+一些微秒,這是這個輸出的原因。在你的代碼中測試這個。

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(); 
    } 
+0

我把定時器放在updatepanel之外,並使用觸發器來調用定時器功能。它解決了我的問題。不管怎麼說,還是要謝謝你 – Kanishka 2011-03-17 10:38:46