Sony ThePony Sony ThePony - 3 months ago 7
jQuery Question

jQuery time left until ... setInterval not working

I am learning to work with dates and I am a little confused.

I am trying to calculate the months: days : hours : mins : secs left until another date.

I am close, but I am stuck on the updating the time left every second, why is my setInterval not updating every 1 sec?



$(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/>




Answer

You need to define currentDate to be the current Date(), not 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/>