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

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

我能做到吗?



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>

最佳答案

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

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>

关于javascript - 倒数至午夜,每天刷新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54256629/

10-09 20:52