检查interval是否存在,如果存在则清除interval并开始新的interval

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

我正在编写倒计时日期脚本。但是,我工作的环境不会在提交时刷新页面,因此我遇到了创建多个间隔的问题。我相信是否有办法检查是否有间隔 运行,然后清除它并创建一个新间隔。但我不确定该怎么做。当然,如果有比我目前的代码设置更好的策略,那么也欢迎提供。

我的代码:

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

为已停止的间隔 ID 调用 clearInterval 不是错误。所以你可以做

clearInterval(intervalId);
intervalId = setInterval(.....);

恐怕没有如何在没有返回值的情况下清除所有声明的间隔。但是你可以在第一次 运行 时保存对全局 window 对象的引用,这样你就可以随时重置它:

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