HTML DOM console.time() Method


The HTML DOM console.time() method is used for displaying the time elapsed in executing a piece of code. This helps us in analyzing the entire code or specific bits of our code. By timing your code you can make it more efficient. Using the optional label parameter you can create several timers on the same page.

Syntax

Following is the syntax for HTML DOM console.time() method −

console.time(label)

Here, the label is an optional parameter to give our timer a name.

Example

Let us look at an example for the console.time() 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>

Press F12 key to view the performance result in your console view

</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 executing code is kept inside the console.time() and console.timeEnd() method. The time taken by the code to finish executing is then displayed in the console window −

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");
}

Updated on: 13-Aug-2019

27 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements