JavaScript Console time() Tutorial

In this section, we will learn what the console time() method is and how to use it in JavaScript.

JavaScript Console time() Method

For testing purposes, sometimes we want to know how long an operation will take.

In situations like this, we can use the `time()` method.

When we call this method, a timer will start counting. Now to stop the timer and print the result on the console, we use the `timeEnd()` method.

The `time()` method takes one optional argument, and that is a label name for the timer.

After running a timer via `time()` method, we call the `timeEnd()` and pass the label to stop the target timer and get the result on the browser console.

Note:

  • After running the `timeEnd()` method on a timer, that timer will stop and won’t count anymore. This means if you need a counter again, you need to create a new one.

Console time() Method Syntax:

console.time(label)

Console time() Method Parameter:

The `time()` method takes one optional argument and that is a label name for the timer.

Console time() Method Return Value:

The method does not return a value.

Example: using Console time() method in JavaScript

console.time("for-loop");

for(let i = 0; i<1000000; i++){

}

console.timeEnd("for-loop");

Output:

for-loop: 4.3359375 ms

Here, the time that it took to run an empty for-loop for about one million times was 4.33 milliseconds.

Leave a Reply