为什么我在倒计时中的代码变为负数

why my codes in countdown turns negative

本文关键字:代码 倒计时 为什么      更新时间:2023-09-26
function ShowTime() {
  var now = new Date();
  var hrs = 19-now.getHours();
  var mins = 60-now.getMinutes();
  var secs = 60-now.getSeconds();
      timeLeft = "  " +hrs+'      '+mins+'      '+secs+' ';
  $("#countdown").html(timeLeft);
}
var countdown;
function StopTime() {
    clearInterval(countdown);
}
setInterval(ShowTime ,1000);

晚上8:30。 我希望如果他到了晚上9点,倒计时再次重新开始,每晚上9点重新启动一次......然后变成负数。

function ShowTime() {
  var now = new Date();
var hrs;
var currentHours = now.getHours();
if(currentHours>19){
hrs = 24-currentHours+19;
}else{
  hrs = 19-now.getHours();
}
  var mins = 60-now.getMinutes();
  var secs = 60-now.getSeconds();
      timeLeft = "  " +hrs+'      '+mins+'      '+secs+' ';
  $("#countdown").html(timeLeft);
}

如果你想使用clearInterval,你应该分配countdown值:

countdown = setInterval(ShowTime ,1000);

请使逻辑像这样。

If now >19 then
timeLeft is (24-now)+19
else hrs = 19-now;