2017-04-07 84 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 –