停止倒计时并每天显示消息

时间:2014-11-27 04:02:56

标签: javascript reset countdown

我有以下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);

2 个答案:

答案 0 :(得分: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();




答案 1 :(得分:0)

试试这个脚本:

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