Search code examples
javascriptintervals

Check if interval exists, if so, clear the interval and start a new one


I'm working on a countdown date script. However, the environment I'm working in does not refresh the page on submission, so I'm having an issue with multiple intervals being created. I believe if there was a way to check if there is an interval running, then to clear it and create a new one. But I'm not sure of how to do this. Of course, if there is a better strategy than how I currently have my code set up, then feel free to provide that as well.

My Code:

//get ready for a-togglin'
var finishedMessage = document.getElementById('finshedMessage');
//get dates value
var dateValue = document.getElementById('dateInput').innerText;

var dateEntered = new Date(dateValue);

//set the date we're counting down too
var targetDate = new Date(dateEntered).getTime();

//Update the countdown every second
var countInterval = setInterval(function() {
  var now = new Date().getTime();

  //get time remaining from now
  var timeRemaining = targetDate - now;

  //time calculations : days, hours, minutes and seconds
  var days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
  var hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);

  //When the countdown is finished, report back completion text
  if (timeRemaining <= 0 || NaN) {
    finishedMessage.style.display = "inline-block";
    clearInterval(countInterval);
  } else {
    //if day is over a year count the years remaining if no years just count       days
    if (days > 365) {
      var years = Math.floor(days / 365);
      days = days % 365;
      document.getElementById("report").innerHTML = years + "Y " + days + "D " + hours + "H " + minutes + "M " + seconds + "s ";
    } else {
      //report the remaining time to report div
      document.getElementById("report").innerHTML = days + "D " + hours + "H " + minutes + "M " + seconds + "s ";
    }
  }
}, 1000);

Solution

  • I'm afraid there's not how to clear all intervals declared without having the value returned from them. But you can save the reference to the global window object when running it for the first time, so you can reset it whenever you want:

    if (window.countInterval) clearInterval(window.countInterval)
    window.countInterval = setInterval(function () {
      /* your code here */
    })