I’m working on my first jQuery plugin which is a simple countdown timer with an option to set the target date. The goal is to get a plain text clock counting down to the provided target date & time. For the life of me I can’t figure out how to use setTimeout or setInverval within the plugin so it actually counts down. Spent all day digging through stackoverflow and other sources but couldn’t find a solution, so apologies if I’m just not getting it.
Here’s what I’ve got:
(function( $ ){
$.fn.clock = function( options ) {
// ESTABLISH DEFAULTS
var settings = $.extend( {
'target' : '07/21/2013 09:00:00', // mm/dd/yyyy hh:mm:ss
}, options);
return this.each(function() {
// calculate milliseconds to target
tarDate = new Date(settings.target);
dateNow = new Date();
amount = tarDate.getTime() - dateNow.getTime();
delete dateNow;
// set label
label = settings.title;
// generate output
if(amount <= 0) {
out = '000:00:00:00';
} else {
td = 0; th = 0; tm = 0; ts = 0; out = ''; // reset everything
amount = Math.floor(amount/1000); // kill the milliseconds
td = Math.floor(amount/86400); // calculate days to target
amount = amount%86400; // convert amount to days
th = Math.floor(amount/3600); // calculate hours to target
amount = amount%3600; // convert amount to hours
tm = Math.floor(amount/60); // calculate minutes to target
amount = amount%60; // convert amount to minutes
ts = Math.floor(amount)+1; // calculate seconds to target
out += (td<=99?'0':'') + (td<=9?'0':'') + td + ':';
out += (th<=9?'0':'') + th + ':';
out += (tm<=9?'0':'') + tm + ':';
out += (ts<=9?'0':'') + ts;
}
// assemble and pump out to dom
$(this).html(out);
// set refresh rate
??????
});
};
})( jQuery );
Check out this link for an interesting pattern for plugin authoring. Basically what you need to do is provide a “method” for updating your clock:
Then, every time you want to update an element, you call it this way:
(from outside; if
updateClockis accessible from your scope, you can call it directly for efficiency. Just remember to wrap the element in$()if necessary)Lastly, you have to configure
setTimeoutorsetInterval. I would prefer setTimeout, because that will allow you to stop or restart your clock if necessary. Add this to the end of your updateClock, maybe preceeded by a check: