admin管理员组

文章数量:1399823

I have this countdown script, it's a simple countdown.

I need to update this countdown to run untl the mignight of the day, so when the user access in different hours will calculate the countdown until midnight and it refreshs every day.

Ho can I do this?

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>

I have this countdown script, it's a simple countdown.

I need to update this countdown to run untl the mignight of the day, so when the user access in different hours will calculate the countdown until midnight and it refreshs every day.

Ho can I do this?

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>

Share Improve this question edited Jan 18, 2019 at 15:19 Victor asked Jan 18, 2019 at 15:06 VictorVictor 531 silver badge6 bronze badges 3
  • 2 This is too broad. You did not specify an exact problem. Is there an exception in your code or are you experiencing unexpected behavior? – creativecreatorormaybenot Commented Jan 18, 2019 at 15:07
  • This doesn't work until the midnight of the day, it's only one 24 hours countdown – Victor Commented Jan 18, 2019 at 15:16
  • I need to update this countdown to run untl the mignight of the day, so when the user access in different hours will calculate the countdown until midnight. – Victor Commented Jan 18, 2019 at 15:21
Add a ment  | 

3 Answers 3

Reset to default 4

This is my solution, it should be fullfil all your requirement:

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>

First, you need to calculate remaining time:

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

let now = new Date();

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

Afterwards, it is necessary to display the time:

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

I finally optimized the code so as not to calculate midnight each time and support several displays without recalculating each time.

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>

You set the deadline to the current time plus 24 h. That is a problem because you want to count only until midnight. The date of midnight of the next day you can get the current date and time and add 24 h to get the next day. With

dat.setHours(0, 0, 0);

you finally set the Time of the next day to midnight. Here the whole code for the deadline.

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

本文标签: javascriptCountdown to midnightrefresh every dayStack Overflow