如何实现倒计时器,当电源关闭或网页关闭时可以暂停?

时间:2015-09-07 17:13:37

标签: c# timer

以秒为单位的剩余时间将作为float存储在数据库中(也将计算毫秒数)

我的计时器刻度将减少秒数(包括毫秒数),具体取决于上次通话和当前通话之间的通过时间

使用.txt作为存储实现如下:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Session["syncCountdownTimer"] = DateTime.Now.ToString();
        timerCountdown.Enabled = true;
        timerCountdown.Interval = 1000;
    }
    DecreaseSeconds();
}

protected void timerCountdown_Tick(object sender, EventArgs e)
{
    DecreaseSeconds();
}

private void DecreaseSeconds()
{
    double seconds = GetCountdown();
    String testSync = Session["syncCountdownTimer"].ToString();
    Session["syncCountdownTimer"] = DateTime.Now;
    DateTime syncLastDateTime = DateTime.Parse(testSync);
    TimeSpan substructed = DateTime.Now.Subtract(syncLastDateTime);
    double syncSeconds = substructed.TotalSeconds;

    seconds -= syncSeconds;

    int hour = (int)seconds / 3600;
    int min = (int)seconds % 3600 / 60;
    int sec = (int)seconds % 3600 % 60;

    lblCountdownStatus.Text = (hour < 10 ? "0" + hour : "" + hour) + ":" +
                              (min < 10 ? "0" + min : "" + min) + ":" +
                              (sec < 10 ? "0" + sec : "" + sec);
    SetCountdown(seconds);
}

private double GetCountdown()
{
    string filename = @"D:\countdown.txt";
    TextReader reader = File.OpenText(filename);
    double seconds = double.Parse(reader.ReadLine());
    reader.Close();
    return seconds;
}

private void SetCountdown(double seconds)
{
    string filename = @"D:\countdown.txt";
    TextWriter writter = File.CreateText(filename);
    writter.WriteLine(seconds);
    writter.Close();
}

最终实施要求:

  • 确保连接延迟
  • 安全性(计时器滴答无法更改为获得更多时间进行测验)
  • 当浏览器关闭或突然断电时,播放器时间应该停止

欢迎任何其他想法

1 个答案:

答案 0 :(得分:0)

时间减少应该在服务器端实现。服务器上的每个减量都应该伴随数据库更新。这样,如果网页被关闭并重新打开,下一个减量将从它停止的地方继续。下面的JS是客户端脚本,它将调用服务器处理程序并更新UX。

JS:

setTimeout(decrementTime, 1000);
function decrementTime() {
  // call Server
}
function decrementTimeCallback() {
   // updateUIWithServerTime
}