2016-09-06 50 views
1

我正在學習使用日期,我有點困惑。jQuery的時間,直到... setInterval不工作

我想計算月份:days:hours:mins:secs left until another day。

我很接近,但我堅持更新每秒剩下的時間,爲什麼我的setInterval不會每1秒更新一次?

$(document).ready(function(){ 
 

 
var currentDate = new Date(); 
 
var futureDate = new Date(2016, 08, 07 , 14 , 33, 20); 
 

 
    //display current and future date 
 
$('#currentDate').text(currentDate); 
 
$('#futureDate').text(futureDate); 
 
    
 
    
 
    //count down 
 
var countDown = setInterval(function() { 
 
\t \t \t var timeLeft = new Date(); 
 
\t \t \t timeLeft = futureDate - currentDate; 
 
     var seconds= Math.floor((timeLeft/1000)%60); 
 
\t \t \t var minutes= Math.floor((timeLeft/(1000*60))%60); 
 
\t \t \t var hours= Math.floor((timeLeft/(1000*60*60))%24); 
 
\t \t \t var dayz= Math.floor((timeLeft/(1000*60*60*24))%31); 
 
     $('#timeLeft').text(dayz + " " + hours + " " + minutes + " " + seconds); 
 
     //return (dayz + " " + hours + " " + minutes + " " + seconds); 
 
}, 1000); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
Current Date: <span id="currentDate"></span><br/> 
 
Future Date: <span id="futureDate"></span><br/> 
 
Time till: <span id="timeLeft"></span><br/>

+0

VAR秒onds = Math.floor((timeLeft/1000)%60); –

+0

是的,對不起,由於格式稍微有點奇怪誤讀。 – DBS

回答

2

您需要定義currentDate是當前Date(),不timeLeft

var currentDate = new Date(); 

$(document).ready(function() { 
 
    var currentDate = new Date(); 
 
    var futureDate = new Date(2016, 08, 07, 14, 33, 20); 
 

 
    //display current and future date 
 
    $('#currentDate').text(currentDate); 
 
    $('#futureDate').text(futureDate); 
 

 
    //count down 
 
    var countDown = setInterval(function() { 
 
    var currentDate = new Date(); // < change this variable's name 
 
    var timeLeft = futureDate - currentDate; 
 
    var seconds = Math.floor((timeLeft/1000) % 60); 
 
    var minutes = Math.floor((timeLeft/(1000 * 60)) % 60); 
 
    var hours = Math.floor((timeLeft/(1000 * 60 * 60)) % 24); 
 
    var dayz = Math.floor((timeLeft/(1000 * 60 * 60 * 24)) % 31); 
 
    $('#timeLeft').text(dayz + " " + hours + " " + minutes + " " + seconds); 
 
    //return (dayz + " " + hours + " " + minutes + " " + seconds); 
 
    }, 1000); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
Current Date: <span id="currentDate"></span> 
 
<br/>Future Date: <span id="futureDate"></span> 
 
<br/>Time till: <span id="timeLeft"></span> 
 
<br/>

+0

啊!當前日期是靜態的,因爲它在setInterval之外!天哪,我真是個傻瓜!謝謝!!!! –

+0

沒問題,很樂意幫忙。作爲參考,當前日期是在循環內部設置的,但是您從未使用它,因爲它被立即覆蓋 –