console.time

console.time

console.time is a function in JavaScript that is used to measure the execution time of a section of code. It works as follows:

  1. You call console.time("name") to start a timer with a specific name

  2. Execute the code to be measured.

  3. You call console.timeEnd("name") to stop the timer.

After stopping the timer, a message will be displayed in the console indicating how much time has elapsed since the timer was started until it was stopped. The message will look like this: name: time ms

console.timeLog is similar to console.timeEnd, but instead of stopping the timer, it simply logs the elapsed time to the console and allows you to continue counting the time. These methods are useful for measuring the execution time of specific sections of code and verifying their efficiency.


async function myFunction() {
  await new Promise(resolve => setTimeout(resolve, 1000));
}

async function test() {
  console.time('timer');
  await myFunction();
  console.timeLog('timer'); // 'timer: 1003ms'
  await myFunction();
  console.timeEnd('timer'); // 'timer: 2005ms'
}

test();

performance.now

Both console.time and performance.now are two different ways of measuring time in JavaScript.

console.time is a function that provides an easy way to measure the execution time of a specific section of code and display the results in the console. It is a simple and useful tool for debugging and optimising code performance.

On the other hand, performance.now is a more precise and advanced function that provides a high-resolution time measurement in milliseconds. It is part of the JavaScript Performance API, which provides detailed information about the performance of a page.

It is recommended to use performance.now when a more precise time measurement is required and detailed information about page performance is desired, while console.time is a more suitable option for quick and easy debugging and optimisation of code.