首页 > 解决方案 > 检查间隔是否存在,如果存在,清除间隔并开始一个新的

问题描述

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

我的代码:

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

标签: javascriptintervals

解决方案


恐怕没有如何清除所有声明的间隔而不从它们返回值。但是您可以在第一次运行时保存对全局window对象的引用,以便您可以随时重置它:

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

推荐阅读