JS Timer

Hi, I have been researching a few different js count down timer scripts. I need to display a simple timer that counts down from mid night.

Some of the scripts that I found seem to be a few years old (but still seem to work fine).

Can any of you JS experts recommend a good script to use as I would like to use something that is up to date, thanks in advance for your help

How do you count down from midnight? Count down to what?

Do you really mean count down to midnight or count up from midnight?

In either case, it’s only a couple of lines of code using setInterval().

Hi, sorry for the late reply… when the page opens, the timer needs to count the time down to mid-night from the current time

From the clients local time, the time of the server, the time where the business is, or your own time?

Apologies, from the current server time and then count the time down like the timers on ebay where by you can see the seconds tick away

JavaScript runs on the clients computer, so the time will need to be provided from the server, commonly done with PHP.
From that time from the server, JavaScript can perform its countdown.

Here’s one where the server can set the day, hour, min, etc…

Ok cool, thanks, i will look into this

You could find pretty much everything you need regarding JavaScript Dates at the Mozilla Dev Network page for Date.

Of course the logic for this is the hard part, it would be pretty easy to get the time for the coming midnight and subtract the current time from it, to give you a remainder of seconds. Then you can use some division and modular math to work our how many hours, seconds and minutes you have to build your countdown clock.

Once you have the difference between “now” and midnight in seconds, you could use a function like the below to format your result:


function formattedTimeFromSeconds( seconds ) {
    //define our immutable values
    var _HOUR = 3600,
        _MINUTE = 60,
        _SECOND = 1;
    
    // find out how many hours there are left
    hours = Math.floor( seconds / _HOUR );
    
    /*
      we can now work out how many seconds are left we need to check
      that we have more than 1 hour if we want to attempt modular math,
      otherwise it will just return the total amount of seconds
    */
    secondsLeft = hours > 0 ? seconds % _HOUR : seconds;

    //work out how many minutes remain
    minutes = Math.floor( secondsLeft / _MINUTE );
    
    //finally, we'll know how many seconds are left.
    secondsLeft = minutes > 0 ? seconds % _MINUTE : seconds;
    
    //we'll return padded numbers in a nice readable format
    return padNumber( hours, 2 ) + ":" + padNumber( minutes, 2 ) + ":" + padNumber( Math.floor( secondsLeft ), 2 );
}

// if the number's string representation length is less then the requested length
// we pad with 0's
function padNumber( num, len ) {
    
    var numLen = num.toString().length;

    if (numLen < len) {

        for (var i = numLen; i < len; i++) {
            num = "0" + num;
        }

    }

    return num;
}



Full example of working countdown clock with commented code: [URL=“http://jsfiddle.net/GeekyJohn/pCm5f/”]http://jsfiddle.net/GeekyJohn/pCm5f/

Of course if you want the dates/times to originate from the server, it’s a simple matter of passing them in with PHP

Here’s a cleaned up version of that code, with thanks to jsbeautifier.org and [url=“http://jslint.com/”]jslint.com


<div id="cd"></div>
...
<script src="countdowntimer.js"></script>
<script>
// add timing information script from PHP here
</script>

Countdown timer script in countdowntimer.js


// Countdown Javascript
// copyright 20th April 2005, 11th March 2011 by Stephen Chapman
// permission to use this Javascript on your web page is granted
// provided that all of the code in this script (including these
// comments) is used without any alteration
// you may change the start function if required
function setC(month, day, dow, hour, min, tz) {
    var toDate = new Date(),
        fromDate = new Date(),
        diffDate = new Date(0);
    if (day.substr(0, 1) === '+') {
        day = parseInt(day.substr(1), 10);
        toDate.setDate(toDate.getDate() + day);
    } else {
        toDate.setDate(day);
    }
    if (month === '*') {
        toDate.setMonth(toDate.getMonth() + 1);
    } else if (month > 0) {
        if (month <= toDate.getMonth()) {
            toDate.setFullYear(toDate.getFullYear() + 1);
        }
        toDate.setMonth(month - 1);
    }
    if (dow > 0) {
        toDate.setDate(toDate.getDate() + (dow - 1 - toDate.getDay()) % 7);
    }
    toDate.setHours(hour);
    toDate.setMinutes(min - (tz * 60));
    toDate.setSeconds(0);
    fromDate = new Date();
    fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());
    diffDate.setMilliseconds(toDate - fromDate);
    return Math.floor(diffDate.valueOf() / 1000);
}

function setCountdown(month, day, dow, hour, min, tz) {
	var m = (month === '*') ? 0 : month,
        c = setC(m, day, dow, hour, min, tz);
    if (month === '*' && c < 0) {
        c = setC('*', day, dow, hour, min, tz);
    }
    return c;
}

function displayCountdown(countdn, cd) {
    var secs = 0,
        mins = 0,
        hours = 0,
        days = 0,
        countdn1 = 0;
    if (countdn < 0) {
        document.getElementById(cd).innerHTML = "Sorry, you are too late.";
    } else {
        secs = countdn % 60;
        if (secs < 10) {
            secs = '0' + secs;
        }
        countdn1 = (countdn - secs) / 60;
        mins = countdn1 % 60;
        if (mins < 10) {
            mins = '0' + mins;
        }
        countdn1 = (countdn1 - mins) / 60;
        hours = countdn1 % 24;
        days = (countdn1 - hours) / 24;
        document.getElementById(cd).innerHTML = days + ' days + ' + hours + ' : ' + mins + ' : ' + secs;
        setTimeout('displayCountdown(' + (countdn - 1) + ',\\'' + cd + '\\');', 999);
    }
}

This is the timing information that PHP needs to add to the page:


// repeat the following code for each countdown timer on your page
var month = '*', // 1 through 12 or '*' within the next month, '0' for the current month
    day = '1',   // day of month or + day offset
    dow = 0,     // day of week sun=1 sat=7 or 0 for whatever day it falls on
    hour = 14,   // 0 through 23 for the hour of the day
    min = 0,     // 0 through 59 for minutes after the hour
    tz = 10,     // offset in hours from UTC to your timezone
    lab = 'cd';  // id of the entry on the page where the counter is to be inserted
displayCountdown(setCountdown(month, day, dow, hour, min, tz), lab);
// end of code to be repeated

If there’s only the one countdown timer on your page, there’s no need to repeat the above script.

Wow, cool, thanks guys… that’s perfect.

Quick question, if i want it to countdown to a midnight at a certain date in the future, for example, let’s say it is for 1 weeks time, is it possible to display the days countdown first and then when it turns into the final day, display the hours:mins:secs

So,

7 days away = 7 days
6 days away = 6 days
5 days away = 5 days
4 days away = 4 days
3 days away = 3 days
2 days away = 2 days
1 day away = 23:59:59 (and counting)

is that possible or would i need to use 2 different types of scripts

Yes that’s possible. You could edit the function called displayCountdown so that it uses the number of days to determine which of the two types of display options you want to use.

Cool, thanks again for your help