Home

Elapsed TimeMack Pexton

Introduction

Count the number of seconds, minutes, hours, and days elapsed.

This version records the start time and computes the number of seconds since start time instead of just counting seconds so it keeps better time.

Demo

elapsed time:

The following tracks the number of minutes since you started viewing this page. Nothing is displayed until a minute has gone by.

elapsed minutes:

Script

<script>
/**
 * 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;
})();
</script>

Minified Script

The following is the above script minified using the YUI Compressor 2.4.4 made available at http://refresh-sf.com/yui/. It reduces the script size to be only 1293 characters.

<script>
(function(){var b={prefix:"",suffix:"",dynamic_labels:true,show_seconds:true,frequency:1000,};var a=function(e,c){if(typeof e=="function"){this.display=e}else{this.el=(typeof e=="string")?document.getElementById(e):e}this.options={};if(!c){c={}}for(var d in b){this.options[d]=(d in c)?c[d]:b[d]}if(!this.options.show_seconds&&!c.frequency){this.options.frequency=60000}};a.prototype={start:function(){this.resume((new Date).getTime())},resume:function(c){if(c){this.startTime=c}var e=this;var d=function(){var j=Math.floor(((new Date).getTime()-e.startTime)/1000);var f=Math.floor(j/60);j%=60;var i=Math.floor(f/60);f%=60;var k=Math.floor(i/24);i%=24;if(e.display){e.display(k,i,f,j)}if(e.el){var g="";if(e.options.dynamic_labels){if(k){g+=k+" day"+(k>1?"s":"")}if(k&&i){g+=", "}if(i){g+=i+" hour"+(i>1?"s":"")}if(i&&f){g+=", "}if(f){g+=f+" minute"+(f>1?"s":"")}if(e.options.show_seconds){if(f&&j){g+=", "}if(j){g+=j+" second"+(j>1?"s":"")}}}else{g+=k+" days "+i+" hours "+f+" minutes";g+=e.options.show_seconds?" "+j+" seconds":""}if(g.length){e.el.innerHTML=(e.options.prefix!=null?e.options.prefix:"")+g+(e.options.suffix!=null?e.options.suffix:"")}}e.timerID=setTimeout(arguments.callee,e.options.frequency)};d()},stop:function(){clearInterval(this.timerID)},};window.ElapsedTimer=a})();
</script>

Examples

Example 1

The basic usage of the script is:

<script></script>

Or if you are using jQuery:

<script>$( function(){(new ElapsedTimer('elapsed_time')).start();} );</script>

Example 2

The followig example does not tick off the seconds. It only changes every minute. The prefix and suffix is not output until the elapsed time is non-zero, or in other words, not until after a minute has past.

<script></script>

Or if you are using jQuery:

<script>
$( function(){(new ElapsedTimer('elapsed_minutes',{prefix:' You started viewing this page ', suffix:' ago.', show_seconds:false})).start();} );
</script>