【问题标题】:jQuery time left until ... setInterval not workingjQuery 剩余时间直到 ... setInterval 不起作用
【发布时间】:2016-09-06 15:17:03
【问题描述】:

我正在学习使用日期,但我有点困惑。

我正在尝试计算月份:天:小时:分钟:距离另一个日期的秒数。

我很接近,但我卡在每秒更新剩余时间上,为什么我的 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() {
			var timeLeft = new Date();
			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/>

【问题讨论】:

  • var seconds= Math.floor((timeLeft/1000)%60);
  • 是的,由于格式有点奇怪,很抱歉误读。

标签: jquery


【解决方案1】:

您需要将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/>

【讨论】:

  • 啊!当前日期是静态的,因为它在 setInterval 之外!天哪,我真是个傻瓜!谢谢!!!!
  • 没问题,很高兴为您提供帮助。作为参考,当前日期是在循环内设置的,但您从未使用它,因为它会立即被覆盖
猜你喜欢
  • 2018-02-03
  • 2020-05-20
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-04
  • 1970-01-01
  • 2012-03-31
相关资源
最近更新 更多