2016-09-06 65 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

没问题,很乐意帮忙。作为参考,当前日期是在循环内部设置的,但是您从未使用它,因为它被立即覆盖 –