倒数至午夜,每天刷新

时间:2019-01-18 15:06:39

标签: javascript html css

我有这个倒计时脚本,这是一个简单的倒计时。

我需要更新此倒数计时才能在一天的半夜运行,因此当用户在不同时间访问时,将计算倒计时直到午夜,并且每天刷新。

我该怎么办?

var timeInMinutes = 1440;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInMinutes * 60 * 1000);

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  return {
    'total': t,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

initializeClock('clockdiv', deadline);
initializeClock('clockdiv2', deadline);
<div id="clockdiv"><span class="minutes"></span>:<span class="seconds"></span></div>

<div id="clockdiv2"><span class="minutes"></span>:<span class="seconds"></span></div>

<div id="clockdiv3"><span class="minutes"></span>:<span class="seconds"></span></div>

3 个答案:

答案 0 :(得分:1)

首先,您需要计算剩余时间:

let nextMidnight = new Date();
nextMidnight.setHours(24,0,0,0);

let now = new Date();

let remainingTimeInSeconds = (nextMidnight.getTime() - now.getTime())/1000;

然后,需要显示时间:

const hours = Math.floor(rest/3600);
rest = rest-(hours*3600);
const minutes = Math.floor(rest/60);
rest = rest-(minutes*60);
const seconds = Math.floor(rest);

console.log(hours, ':', ("0" + minutes).slice(-2), ':', ("0" + seconds).slice(-2));

我最终优化了代码,以免每次都不计算午夜,并且支持多次显示而无需每次重新计算。

const Countdown = (() => {

  let nextMidnight = new Date();
  nextMidnight.setHours(24,0,0,0);

  const getRemainingTime = () => {
    let now = new Date();

    let time = (nextMidnight.getTime() - now.getTime())/1000;
    
    if(time < 0) {
      nextMidnight = new Date();
      nextMidnight.setHours(24,0,0,0);
      
      return getRemainingTime();
    }
    
    return time;
  }
  
  const parseTime = (time) => {
    const hours = Math.floor(time/3600);
    let rest = time-(hours*3600);
    const minutes = Math.floor(rest/60);
    rest = rest-(minutes*60);
    const seconds = Math.floor(rest);
    const milliseconds = (rest-seconds)*1000;

    return [hours, minutes, seconds, milliseconds];
  };
  
  const formatTime = (parsedTime) => {
      return '<span class="hours">' + parsedTime[0] + '</span><span class="hSep">:</span><span class="minutes">' + ("0" + parsedTime[1]).slice(-2) + '</span><span class="mSep">:</span><span class="seconds">' + ("0" + parsedTime[2]).slice(-2) + '</span>';
  };
  
  const els = [];
  let timeout;
  
  return (el) => {
    els.push(el);
    
    if(!timeout) {
    
      const refresh = () => {
        const parsedTime = parseTime(getRemainingTime());
        const formattedTimes = formatTime(parsedTime);
        
        for(let i = 0, iend = els.length; i < iend; i++) {
          els[i].innerHTML = formattedTimes;
        }
        
        setTimeout(() => {
          refresh();
        }, parsedTime[3]);
      };
      refresh();
      
    }
    else el.innerHTML = formatTime(parseTime(getRemainingTime()));
  };

})();

Countdown(document.getElementById('countdown'));
Countdown(document.getElementById('countdown-two'));
.departure {
  font-size: 1.5em;
}

#countdown {
  padding: 5px;
  border: 1px solid black;
  display: inline-block;
  padding: 14px;
  border-radius: 5px;
}
.departure #countdown .span {
  display: inline-block;
}

.departure .hours, .departure .minutes, .departure .seconds{
  color: #fff;
  background: #000;
  background: linear-gradient(to top, #444 0%, #444 50%, #000 50%, #000 100%);
  border-radius: 6px;
  padding: 10px;
  font-family: arial;
}

.departure .hSep, .departure .mSep {
  padding: 5px;
}
<div class="departure"><span id="countdown"></span> ✈</div>
<br />
<div id="countdown-two"></div>

答案 1 :(得分:0)

您将截止日期设置为当前时间加上24小时。这是一个问题,因为您只想计数到午夜。 第二天的午夜日期可以获取当前日期和时间,并加上24小时以获取第二天。与

dat.setHours(0, 0, 0);

您终于将第二天的时间设置为午夜。 这是截止日期的完整代码。

var dat = new Date();
dat.setHours(dat.getHours() + 24);
dat.setHours(0, 0, 0);

答案 2 :(得分:0)

这是我的解决方案,应满足您的所有要求:

var div=document.getElementById("bb");
 
setInterval(function(){ 
  var toDate=new Date();
  var tomorrow=new Date();
  tomorrow.setHours(24,0,0,0);
  var diffMS=tomorrow.getTime()/1000-toDate.getTime()/1000;
  var diffHr=Math.floor(diffMS/3600);
  diffMS=diffMS-diffHr*3600;
  var diffMi=Math.floor(diffMS/60);
  diffMS=diffMS-diffMi*60;
  var diffS=Math.floor(diffMS);
  var result=((diffHr<10)?"0"+diffHr:diffHr);
  result+=":"+((diffMi<10)?"0"+diffMi:diffMi);
  result+=":"+((diffS<10)?"0"+diffS:diffS);
  div.innerHTML=result;
  
},1000);
<div id="bb">
</div>