在实际倒计时后进行不同的倒计时

时间:2017-11-03 18:34:50

标签: javascript html

我需要帮助进行下一次倒计时。当实际倒计时结束时,我需要用新的不同日期重置实际倒计时。所有这一切都在一个简单的柜台

$(function (){

function countdown() {

var now = new Date();
var eventDate = new Date('Nov 03, 2017 13:02:20');
var secondEventDate =  new Date('Nov 09, 2017 10:18:40');
var currentTime = now.getTime();
var evenTime = eventDate.getTime();

if(eventDate<=currentTime){
    document.getElementById("countdown").innerHTML = "expired";
    clearInterval(setTimeout);

}

var remTime = evenTime - currentTime;

var sec = Math.floor(remTime / 1000);
var min = Math.floor(sec / 60);
var hur = Math.floor(min / 60);
var day = Math.floor(hur / 24);

 hur %= 24;
 min %= 60;
 sec %= 60;

hur = (hur < 10) ? "0" + hur : hur;
min = (min < 10) ? "0" + min : min;
sec = (sec < 10) ? "0" + sec : sec;

$('.seconds').text(sec);
$('.minutes').text(min);
$('.hours').text(hur);
$('.days').text(day);

setTimeout(countdown, 1000);
}

countdown();


});

1 个答案:

答案 0 :(得分:0)

让我们清理一下代码。起初我们需要一些辅助函数:

const addZero = n => n < 10 ? "0" + n : n;
const format = ms => {
   const result = [];
   [1000,60,60,24,31].reduce((carry, max) => {
      result.unshift(carry % max);
      return Math.floor(carry / max);
   },ms);
   result.pop();//remove milliseconds
   return result.map(addZero).join(":");
};

所以现在我们需要一个Timer,就像这样:

class Timer {
  constructor(to, el, finish){
    this.to = to;
    this.el = el;
    this.finish = finish;
    setTimeout(_ => this.update(), 1000);
  }
  update(){
    const ms = this.to - Date.now();
    this.el.innerHTML = format(ms);
    if(ms < 0){
       this.finish();
    }else{
      setTimeout(_ => this.update(), 1000);
    }
  }
}

所以要设置计时器:

new Timer(
   new Date('Nov 03, 2017 13:02:20'),
   document.body,
   () => new Timer(
      new Date('Nov 03, 2017 13:02:20'),
      document.body, 
      _ => _
   )
);

Try it