重置并重启javascript倒计时(循环)

时间:2016-02-08 16:06:55

标签: javascript loops countdown

我有基于日期对象的纯JavaScript倒计时,一切正常,但我希望倒计时继续运行。

JSFiddle sample

//the countdown part

var d = new Date();
var theDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
var newTime = new Date(Date.parse(d) + secs * 1000);
//var end = new Date('02/08/2016 10:00:00');
var end = newTime;
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
if (timer) clearInterval(timer);

function showRemaining() {

  var now = new Date();
  var distance = end - now;
  if (distance < 0) {
    clearInterval(timer);
    document.getElementById('countdown').innerHTML = 'this is the callback from here should reset and starts again';
    return;
  }
  var days = Math.floor(distance / _day);
  var hours = Math.floor((distance % _day) / _hour);
  var minutes = Math.floor((distance % _hour) / _minute);
  var seconds = Math.floor((distance % _minute) / _second);

  document.getElementById('countdown').innerHTML = days + 'days ';
  document.getElementById('countdown').innerHTML += hours + 'hrs ';
  document.getElementById('countdown').innerHTML += minutes + 'mins ';
  document.getElementById('countdown').innerHTML += seconds + 'secs';

}

timer = setInterval(showRemaining, 1000);

1 个答案:

答案 0 :(得分:0)

if (distance < 0)分支中,您只需删除clearInterval并重置end变量即可。

这样的事情:

if (distance < 0) {
  d = new Date();
  theDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
  newTime = new Date(Date.parse(d) + secs * 1000);
  end = newTime;
  return;
}