Core JavaScript

Timing with the Performance Function

The performance.now() function can be used to get high resolution timings of portions of code.

Performance.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="Performance.js"></script>
</body>
</html>

Performance.js

const kiStart = performance.now();
// Get the body element
var qBody = document.getElementsByTagName("body")[0];
for (var i = 1; i <= 10; i++) {
	var qNewDiv = document.createElement("div");
	qNewDiv.innerHTML = "Count " + i;
	qBody.appendChild(qNewDiv);
	// Delay so that the performance can be measured
	var iDelayStart = Date.now();
	// Date.now() is an alternative function for measuring milliseconds
	let iDelayLoop = null;
	do {
  	iDelayLoop = Date.now();
	} while (iDelayLoop - iDelayStart < 53);
}
const kiEnd = performance.now();

var qElapsedTimeDiv = document.createElement("div");
// The time for the for loop
qElapsedTimeDiv.innerHTML = "Elapsed Time = " + (kiEnd - kiStart) + " milliseconds";
qBody.appendChild(qElapsedTimeDiv);
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.