2017-04-07 75 views
0

我有这个js代码。它的工作原理,但我注意到我得到了这样的错误。 “TypeError:document.getElementById(...)为空” 而我注意到在萤火虫中继续计数的错误。所以我认为这是继续进行的for循环。你能看看下面的代码,告诉我它有什么问题吗?这个javascript代码有什么问题?它不停止循环

<script> 
 
$(document).ready(function() { 
 

 
    //Create object with the list of due dates 
 
    //The 'name' will correspond to the field ID to populate the results 
 
    var dueDates = { 
 
     'date1':'2017-04-17 09:55:18', 
 
     'date2':'2017-05-17 09:55:18', 
 
     'date3':'2017-06-17 09:55:18' 
 
    }; 
 

 
    var timer = setInterval(function() { 
 
     //Instantiate variables 
 
     var dueDate, distance, days, hours, minutes, seconds, output; 
 
     //Set flag to repeat function 
 
     var repeat = false; 
 
     // Get todays date and time 
 
     var now = new Date().getTime(); 
 
     //Iterate through the due dates 
 
     for (var dueDateId in dueDates) { 
 
      //Get the due date for this record 
 
      dueDate = new Date(dueDates[dueDateId]); 
 
      // Find the distance between now an the due date 
 
      distance = dueDate - now; 
 
      // Time calculations for days, hours, minutes and seconds 
 
      days = Math.floor(distance/(1000 * 60 * 60 * 24)); 
 
      hours = Math.floor((distance % (1000 * 60 * 60 * 24))/(1000 * 60 * 60)); 
 
      minutes = Math.floor((distance % (1000 * 60 * 60))/(1000 * 60)); 
 
      seconds = Math.floor((distance % (1000 * 60))/1000); 
 
      //Determine the output and populate the corresponding field 
 
      output = "OVERDUE"; 
 
      if (distance > 0) 
 
      { 
 
       output = days + "d " + hours + "h " + minutes + "m " + seconds + "s"; 
 
       repeat = true; //If any record is not expired, set flag to repeat 
 
      } 
 
      document.getElementById(dueDateId).innerHTML = output; 
 
      //If flag to repeat is false, clear event 
 
      if(!repeat) 
 
      { 
 
       clearInterval(timer); 
 
      } 
 
     } 
 
    }, 1000); 
 
}); 
 
</script>
<div id="date1"></div> 
 
<div id="date2"></div> 
 
<div id="date3"></div>

+0

Google'setInterval'。 – Azim

+0

“重复”变量在您的代码中始终为真。 !重复始终评估为false,clearInterval永远不会执行 – jrook

+0

还有** 2个月和10天**直到2017-06-17 09:55:18',所以这将循环100天! –

回答

1

你的第一个到期日是未来,所以距离是正的,所以重复在循环的第一个迭代设置为true。因为它在循环内再次不会变为false,所以for循环迭代中的任何一个都不会执行clearInterval函数。所以setInterval回调将在1秒后再次被调用,并且相同的逻辑重复...

+0

100天准确:D! '2017-06-17'遥远的将来! –

+0

是的,我正在倒数3个不同的日期。在我使用mysql数据库日期进行测试之前,只有两个日期处于活动状态,第三个日期是空的。这就是为什么它给了我循环错误。但是如果我已经填满了所有3个日期,那么我不会再犯错。 –

+0

我通过这样做解决了这个问题,如果日期为空,if语句将被隐藏。 https://paste.ofcode.org/bFjCDVbdxKswPBqSSih7vR –