How to measure the running time of a function in JavaScript?

December 1, 2020 - 2 min read

To measure the running time of a function or a task we can use the console.time() and console.timeEnd() methods in JavaScript.

Let's say we have a function like this which takes some time to complete,

// function which takes some time
function bigTimeFunction() {
  for (let i = 0; i < 1000; i++) {
    console.log("🌟");
  }
}

Let's measure the time taken for the bigTimeFunction() function to execute.

Here, before invoking the bigTimeFunction we need to use the console.time() method to start the timer and we need to pass a name for the timer as an argument to the method.

Let's name the timer the same name as the function that is bigTimeFuction.

It can be done like this,

// function which takes some time
function bigTimeFunction() {
  for (let i = 0; i < 1000; i++) {
    console.log("🌟");
  }
}

// start the timer using console.time
// pass the name of the timer as an
// argument to the method
console.time("bigTimeFuction");

// invoke the function
bigTimeFunction();

Now let's end the timer by using the console.timeEnd() method after invoking the bigTimeFuction() function and pass the same name of the timer to the method as an argument.

NOTE: The name should match for both the console.time() and console.timeEnd() methods to start and stop the timer correctly.

// function which takes some time
function bigTimeFunction() {
  for (let i = 0; i < 1000; i++) {
    console.log("🌟");
  }
}

// start the timer using console.time()
// pass the name of the timer as an
// argument to the method
console.time("bigTimeFuction");

// invoke the function
bigTimeFunction();

// stop the timer using console.timeEnd()
// pass the same name used in console.time() method
// as an argument to the mehtod
console.timeEnd("bigTimeFuction");
  • The running time will be displayed to the console.

See this example live repl.it.

Feel free to share if you found this useful 😃.