0
votes

I'm trying to create a simple countdown timer to a date/time.

I currently only have the following days to go script which is working fine:

<div id="countdown">

today = new Date();
BigDay = new Date("March 29, 2013");
msPerDay = 24 * 60 * 60 * 1000 ;
timeLeft = (BigDay.getTime() - today.getTime());
e_daysLeft = timeLeft / msPerDay;
daysLeft = Math.floor(e_daysLeft);
document.write(daysLeft + " days to go!");

</div>

I'm now trying to create a full countdown timer (with hours, minutes and seconds) and have created the following script. The html isn't showing on the page.

var today = new Date();
var BigDay = new Date("29 03 2013, 14:30:00");
var msPerDay = 24 * 60 * 60 * 1000 ;
var timeLeft = (BigDay.getTime() - today.getTime());
var e_daysLeft = timeLeft / msPerDay;
var daysLeft = Math.floor(e_daysLeft);
var e_hrsLeft = (e_daysLeft - daysLeft)*24;
var hrsLeft = Math.floor(e_hrsLeft);
var e_minsLeft = (e_hrsLeft - hrsLeft)*60;
var minsLeft = Math.floor(e_minsLeft);
var e_secsLeft = (e_minsLeft - minsLeft)*1000;
var secsLeft = Math.floor(e_secsLeft);
var timeString = daysLeft + " : " + hrsLeft + " : " + minsLeft + " : " + secsLeft;

$('document').ready(function(){

window.setInterval(function(){
$('#countdown').html(timeString);
}, 1000);

});

I'm not sure what the problem might be. The first script is contained within the html, the second is an external js file.

Edit: html is now showing however all values are displayed as NaN.

3
BTW, there's an extra opening bracket in var minsLeft = Math.floor((e_minsLeft); What does your console say? - isotrope
That improved it. It's now showing in html but the values are each showing as NaN. - Razzildinho

3 Answers

12
votes

Other than the mentioned syntax errors there are logical errors also, you need to calculate the remaining time string inside the timeout function otherwise the values are calculated only on page load.

$(function(){
    var BigDay = new Date("29 Mar 2013, 14:30:00");
    var msPerDay = 24 * 60 * 60 * 1000 ;


    window.setInterval(function(){
        var today = new Date();
        var timeLeft = (BigDay.getTime() - today.getTime());

        var e_daysLeft = timeLeft / msPerDay;
        var daysLeft = Math.floor(e_daysLeft);

        var e_hrsLeft = (e_daysLeft - daysLeft)*24;
        var hrsLeft = Math.floor(e_hrsLeft);

        var e_minsLeft = (e_hrsLeft - hrsLeft)*60;
        var minsLeft = Math.floor(e_minsLeft);

        var e_secsLeft = (e_minsLeft - minsLeft)*60;
        var secsLeft = Math.floor(e_secsLeft);


        var timeString = daysLeft + " : " + hrsLeft + " : " + minsLeft + " : " + secsLeft;
        $('#countdown').html(timeString);
    }, 1000);
})

Demo: Fiddle

0
votes

You have an error here: var minsLeft = Math.floor((e_minsLeft);

The first parenthesis isn't closed, should be var minsLeft = Math.floor(e_minsLeft);

0
votes

because you didn't run the timeString calculation every second so the text within your #countdown div will never change