【问题标题】:Stop countdown and display message daily每天停止倒计时并显示消息
【发布时间】:2014-11-27 04:02:55
【问题描述】:

我有以下 javascript 倒数计时器,它应该每天在同一时间重置。在它应该停止和重置的点上,它会继续倒计时到“负时间”。我怎样才能解决这个问题?

----- JSFiddle Link -----

function ShowHour() {
  var now = new Date();
  var hrs = 19-now.getHours();
      hourLeft = +hrs+ '';
  $("#hour").html(hourLeft);
}

function ShowMin() {
  var now = new Date();
  var mins = 60-now.getMinutes();
      timeLeft = +mins+ '';
  $("#min").html(timeLeft);
}

function ShowSec() {
  var now = new Date();
  var secs = 60-now.getSeconds();
      timeLeft = +secs+ '';
  $("#sec").html(timeLeft);
}

var countdown;
function StopTime() {
    clearInterval(countdown);
}

setInterval(ShowHour ,1000);
setInterval(ShowMin ,1000);
setInterval(ShowSec ,1000);

【问题讨论】:

  • 你为什么要19-now.getHours();
  • 是一个比我更懂JS的朋友推荐给我的。

标签: javascript reset countdown


【解决方案1】:

您似乎想在每天晚上 7 点重置它,对吗?

问题出在19-now.getHours()。假设时间是 23 (11:00)。这会给你 -4 小时,而它应该是 20 小时。

解决这个问题应该相当容易。您可以减去 42-now.getHours() 以得到第二天晚上 7 点之前的小时数,然后是模数 24(以确保它是 24 小时制。)

例子:

function hoursUntil7PM(){
    var now = new Date();
    var hrs = (42-now.getHours())%24;
    alert(hrs);
}
hoursUntil7PM();

【讨论】:

    【解决方案2】:

    试试这个脚本:

    var resetHour = 19; /* 7 pm*/
    function hoursLeftUntilReset() {
        var curHours = (new Date()).getHours();
        var hoursLeft = 0;
        if (curHours <= resetHour) {
            hoursLeft = resetHour - curHours;
        } else {
            hoursLeft = (24 - curHours) + resetHours;
        }
        if (hoursLeft == 0) {
            // Call reset function here
        }
        alert('Hours Left to reset:'+ hoursLeft);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多