Reputation: 213
Im making a countdown timer and I want the time to refresh every second. Im using setInterval but it only seems to be running once instead of every second. What is wrong with my code?
var countDown = setInterval(function(){
$('#days').val(daysLeft);
$('#hours').val(hoursLeft);
$('#minutes').val(minLeft);
$('#seconds').val(secLeft);
},1000);
demo: http://jsfiddle.net/EnigmaMaster/pyRR8/14/
Upvotes: 0
Views: 143
Reputation: 3558
want to look like this? I have updated your Jsfiddle
See here : http://jsfiddle.net/pyRR8/23/
Upvotes: 1
Reputation: 6703
Your code was not updating the currentDate
variable. I updated the code on jsFiddle and paste it here:
var endDay = new Date('May 24, 2012 11:30:00');
var countDown = setInterval(function(){
var currentDate = new Date();
var daysdecimal = (endDay - currentDate)/(1000*60*60*24);
var daysLeft = Math.floor(daysdecimal);
var hoursdecimal = (daysdecimal - Math.floor(daysdecimal))*24;
var hoursLeft = Math.floor(hoursdecimal);
var minLeft = 60 - currentDate.getMinutes();
var secLeft = 60 - currentDate.getSeconds();
$('#days').val(daysLeft);
$('#hours').val(hoursLeft);
$('#minutes').val(minLeft);
$('#seconds').val(secLeft);
},1000);
Upvotes: 2
Reputation: 179046
You need to recalculate the time left within the interval, otherwise you'll continue to set it to the same value.
Upvotes: 4