HM Dadou February 2016

Reset and restart javascript countdown (loop)

I have this pure JavaScript countdown based on date object all working fine except that I wanted the countdown to keep running.

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

Answers


Marco February 2016

In the if (distance < 0) branch, you simply need to remove clearInterval and reset the end variable.

Something like this:

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

Post Status

Asked in February 2016
Viewed 2,463 times
Voted 6
Answered 1 times

Search




Leave an answer