The title of this post says it all.
I made a MINI script timer object that counts how long a certain piece of code runs (executes).
It’s very handy for optimizing youre code!

The output is displayed in seconds with 3 digits behind the comma.
if you just want milliseconds remove the “/1000″ from:

this.scriptRunTime = (this.stopTime - this.startTime)/1000;

The code:

/**
 * javascript script timer
 * example:
 * scriptTimer.startTimer();
 * alert('hello');
 * scriptTimer.stopTimer();
 * alert(scriptTimer.scriptRunTime);
 *
 */
var scriptTimer = {
	scriptRunTime : 0,
	startTime : 0,
	stopTime : 0,
	startTimer : function(){
		time = new Date();
		this.startTime = time.getTime();
	},
	stopTimer : function(){
		time = new Date();
		this.stopTime = time.getTime();
		this.scriptRunTime = (this.stopTime - this.startTime)/1000;
	}
}

Working example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>Remorse.nl JavaScript javascript script timer (see how long a script runs)</title>

		<script type="text/javascript"  >
			function init(){
				//start the timer
				scriptTimer.startTimer();
				//some code so see how long it executes
				alert('hello');
				//stop the timer
				scriptTimer.stopTimer();
				//alert the result
				alert(scriptTimer.scriptRunTime);
			}

			/**
			 * javascript script timer
			 * example:
			 * scriptTimer.startTimer();
			 * alert('hello');
			 * scriptTimer.stopTimer();
			 * alert(scriptTimer.scriptRunTime);
			 *
			 */
			var scriptTimer = {
				scriptRunTime : 0,
				startTime : 0,
				stopTime : 0,
				startTimer : function(){
					time = new Date();
					this.startTime = time.getTime();
				},
				stopTimer : function(){
					time = new Date();
					this.stopTime = time.getTime();
					this.scriptRunTime = (this.stopTime - this.startTime)/1000;
				}
			}

		</script>
	</head>
	<body onload="init()">

	</body>
</html>

In this example the timer will stop when u push the ok button of the alert box.

“scriptTimer.startTimer();” : starts the timer place it where you want to start the timer.
“scriptTimer.stopTimer();” : stops the timer place it where you want to stop the timer.

After u called “scriptTimer.stopTimer();” u can call “scriptTimer.scriptRunTime” and alert it or put it in a div to
see how long the script did run.

Instead of an alert box u can make a for loop to see how long it takes to run.
Replace alert(‘hello’) in the function init with code:

for(i=0;i <= 50000; i++){
}

See and feel the difference between Microsoft IE and firefox :) .

That's easy!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Furl
  • LinkedIn
  • StumbleUpon
  • Technorati
  • TwitThis
  • NuJIJ