HTML DOM console.timeEnd() Method

The console.timeEnd() method is used for stopping the timer and displaying the time elapsed while the code inside the console.time() and console.timeEnd() took to finish execution. It is useful for timing sections of your code to figure out where the bottlenecks are. Using the optional label parameter we can specify which timer to stop.

Syntax

Following is the syntax for console.timeEnd() method −

console.timeEnd(label);

Here, label is an optional parameter for specifying which timer to stop.

Example

Let us look at an example for the console.timeEnd() method −

<!DOCTYPE html>
<html>
<body>
<h1>console.time() Method</h1>
<p>Click the below button to time the for,while and do-while loops for 100000 iterations </p>
<button type="button" onclick="LoopPerform()">TIMER</button>
<script>
var i,j,k;
i=0,j=0,k=0;
function LoopPerform(){
console.time("for-loop");
for (; i < 100000; i++){}
console.timeEnd("for-loop");
console.time("while-loop");
while(j<100000)
j++;
console.timeEnd("while-loop");
console.time("do-while loop");
do{k++;}
while(k<100000);
console.timeEnd("do-while loop");
}
</script>
<p>Press F12 key to view the performance result in your console view</p>
</body>
</html>

Output

This will produce the following output −

On clicking the TIMER button −

In the above example −

We have first created a button TIMER that will execute the LoopPerform() function when clicked by the user −

</button type="button" onclick="LoopPerform()">TIMER</button>

The function LoopPerform() has for, while and do-while loops executing inside it. There are total three timers with label “for-loop”, ”while-loop” and “do-while loop” created to gauge performance of the three loops.

The console.time() method starts the timer and takes an optional label parameter and counts the time elapsed while the code inside it is executing. The console.timeEnd() method is used to stop the timer and display the results in the console view. Using labels as parameter in the timeEnd() method allowed us to specify which timer to stop −

function LoopPerform(){
console.time("for-loop");
for (; i < 100000; i++){}
console.timeEnd("for-loop");
console.time("while-loop");
while(j<100000)
j++;
console.timeEnd("while-loop");
console.time("do-while loop");
do{k++;}
while(k<100000);
console.timeEnd("do-while loop");
}
Published on 08-Aug-2019 16:07:17