/** * Display elapsed time. * * Usage: * var t = new ElapsedTimer(display,options); * t.start(); * t.stop(); * t.resume( [startTime] ); * * Parameters: * display -- function to execute to display the count * or DOM element ID where count is to appear * or DOM element * options -- optional options map * * Version 2.0 * Copyright 2006,2010, Mack Pexton, mackpexton.com * License http://www.opensource.org/licenses/mit-license.php */ (function(){ var default_options = { prefix: '', // prefix added to counter display suffix: '', // suffix added to counter display dynamic_labels: true, // if true, labels (hours, minutes) are output as needed show_seconds: true, // if true, seconds is also displayed frequency: 1000, // 1 second in milliseconds }; var timer = function(display,options){ if (typeof display == 'function') { this.display = display; } else { this.el = (typeof display == 'string') ? document.getElementById(display) : display; } this.options = {}; if (!options) options = {}; for (var p in default_options) { this.options[p] = (p in options) ? options[p] : default_options[p]; } if (!this.options.show_seconds && !options.frequency) this.options.frequency = 60000; // change to 1 min. intervals } timer.prototype = { start: function() { this.resume( (new Date).getTime() ); }, resume: function(startTime) { if (startTime) this.startTime = startTime; var obj = this; var ticktock = function() { var s = Math.floor(((new Date).getTime() - obj.startTime)/1000); var m = Math.floor(s/60); s %= 60; var h = Math.floor(m/60); m %= 60; var d = Math.floor(h/24); h %= 24; if (obj.display) obj.display(d,h,m,s); if (obj.el) { var html = ''; if (obj.options.dynamic_labels) { if (d) { html += d + ' day' + (d > 1 ? 's' : ''); } if (d && h) { html += ', '; } if (h) { html += h + ' hour' + (h > 1 ? 's' : ''); } if (h && m) { html += ', '; } if (m) { html += m + ' minute' + (m > 1 ? 's' : ''); } if (obj.options.show_seconds) { if (m && s) { html += ', '; } if (s) { html += s + ' second' + (s > 1 ? 's' : ''); } } } else { html += d + ' days ' + h + ' hours ' + m + ' minutes'; html += obj.options.show_seconds ? ' ' + s + ' seconds' : ''; } if (html.length) { obj.el.innerHTML = (obj.options.prefix != null ? obj.options.prefix : '') + html + (obj.options.suffix != null ? obj.options.suffix : ''); } } obj.timerID = setTimeout(arguments.callee,obj.options.frequency); }; ticktock(); // start timer }, stop: function() { clearInterval(this.timerID); }, }; // Expose window.ElapsedTimer = timer; })();