# Outputting a countdown in a div

I got this code working with the jQuery Countdown Plugin to take a string input and output a countdown in a div. Is there a better way of implementing this?

JSFiddler

HTML

<div id="defaultCountdown"  class="arg">Here</div>


Script

function stringToCountdown(element,str){
/* Parse the String */
var hh = parseInt(str.substr(0,2),10);
var mm = parseInt(str.substr(2,2),10);
var ss = parseInt(str.substr(4,2),10);
var parity = parseInt(str.substr(4,2),10);

var austDay = new Date();
austDay = new Date(    austDay.getFullYear() , austDay.getMonth(),
austDay.getDate(),austDay.getHours()+hh,
austDay.getMinutes()+mm, austDay.getSeconds()+ss );
$('#defaultCountdown').countdown({until:austDay , compact: true,format: 'dHMs',expiryText: 'No More Counter for you'}); }$(function () {
stringToCountdown('#defaultCountdown6','000005');
});


Should I rewrite this to make it simpler and faster?

You may combine var statements and put them top of your function. Strip unused variables like parity and use element variable instead of using #defaultCountdown directly. And lastly, a little formatting will make your code much readable. Here is the result.

If you're trying to accomplish relative countdown, plugin itself supports it. I also put an example to show how to do it.

function stringToCountdown(selector, str){
var hh = parseInt(str.substr(0,2), 10),
mm = parseInt(str.substr(2,2), 10),
ss = parseInt(str.substr(4,2), 10),
austDay = new Date();

austDay = new Date(
austDay.getFullYear(),
austDay.getMonth(),
austDay.getDate(),
austDay.getHours() + hh,
austDay.getMinutes() + mm,
austDay.getSeconds() + ss
);

$(selector).countdown({ until: austDay, compact: true, format: 'dHMs', expiryText: 'No More Counter for you' }); }$(function () {
stringToCountdown('#defaultCountdown','000010');
});


And this is less readable version. There is no extra variable. So it may run a little bit faster.

function stringToCountdown(selector, str){
var austDay = new Date();
$(selector).countdown({ until: new Date( austDay.getFullYear(), austDay.getMonth(), austDay.getDate(), austDay.getHours() + parseInt(str.substr(0,2), 10), austDay.getMinutes() + parseInt(str.substr(2,2), 10), austDay.getSeconds() + parseInt(str.substr(4,2), 10) ), compact: true, format: 'dHMs', expiryText: 'No More Counter for you' }); }$(function () {
stringToCountdown('#defaultCountdown','000010');
});

• Performance is just not an issue here. The first version is clearly better. I would go one step further and create two Date objects for clarity: one called now and one called end. May 22, 2014 at 8:28