【问题标题】:Independent countDown in JavascriptJavascript中的独立倒计时
【发布时间】:2019-01-21 10:40:38
【问题描述】:

我使用final countdown 来倒计时。我提供了一个enddate,它工作正常。

<div class="js-countdown" data-enddate="2019/1/21 15:54"></div>

我的js:

var $clock = $('.js-countdown');
var d = new Date(Date.parse($clock.data("enddate").replace(/ /g, "T")));
  $clock.countdown(d, function(event) {
    $(this).text(
      event.strftime('%D days %H:%M:%S')
    );
  });
</script>

这实际上取决于用户时钟,例如,当用户更改时间或时钟未同步时,倒数计时器无法按预期工作。
服务器时间:13:54
用户时间:13:54
结束日期:15:54,然后倒计时显示:2(hrs):00(mins)。但是如果:
服务器时间:13:54
用户时间:14:54(特意改了)
结束日期:15:54,然后倒计时显示 1(hrs):00(mins),因为我希望它是 2(hrs):00(mins)。我该如何改变这种行为?我的目标是实现一个独立的倒计时。请给我一些提示好吗?

编辑

Here,定时器更新日期。每次更新事件触发时发送请求是否合理?

【问题讨论】:

  • 您需要将日期设置为服务器时间,也许像 worldclockapi.com 这样的东西会有所帮助。获取当前时间的 JSON。
  • 你到底想达到什么目的?独立于服务器时区的完整客户端 coutdown(例如,从单击开始计算一分钟),还是需要与服务器时间同步的可靠 coutdown?如果你想要第二个,永远不要相信客户端时间,并且总是参考服务器时间来检查倒计时是否过期(客户端时间可以在时间设置后更改,并且可以用来滥用计时器)

标签: javascript countdown


【解决方案1】:

我不确定这是否是最好的方法,但到目前为止,它工作正常。

var now;
var it = 1;
now = new Date(Date.parse('@DateTime.UtcNow.ToString("u")'.replace(/ /g, "T")));
setInterval(setAndSyncTime, 1000);
function setAndSyncTime() {
    var t1 = new Date();
    var t2 = now;
    var t3 = Math.abs(t1 - t2);
    if (t3 > 2000) {
        if (it === 10) {
            it = 0;
            $.ajax({
                url: '/SyncTime',
                type: 'get',
                success: function (response) {
                    now = new Date(Date.parse(response.replace(/ /g, "T")));
                }
            });
        } else {
            now = now.setSeconds(now.getSeconds() + 1);
            now = new Date(now);
        }
    } else {
        now = now.setSeconds(now.getSeconds() + 1);
        now = new Date(now);
    }
    it++;
}

public virtual JsonResult SyncTime()
{
    return Json(DateTime.UtcNow.ToString("u"), JsonRequestBehavior.AllowGet);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多