Here’s a JavaScript function that you might not have come across before; the JavaScript time function.
So let’s say you want to time the execution of a function or a set of statements in your JavaScript code.
You could use JavaScript’s built in Date
object and it’s various methods for tracking milliseconds of elapsed time which might look something like this:
const startTime =new Date().getTime();
//do something
const endTime = new Date().getTime();
console.log(`time taken ${(endTime - startTime)/1000} seconds`);
However there is actually a time
function available on the console
object.
Let’s take a look and see what the previous code might look like using this function instead:
console.time('doSomething')
// do something
console.timeEnd('doSomething')
You can see from this code that we start a timer with the console.time
function and then when we’re done doing what we need to do we stop measuring using console.timeEnd
.
You’ll get some output in the browser console that looks something like this:
doSomething: 4ms - timer ended
You’ll notice we’re providing doSomething
as an argument to the time
and timeEnd
functions which is an identifier for the timer and we can use this to label our timers and allow you to have multiple ones running at the same time.
If you have a need to log the time elapsed on the timer at any point you can use the timeLog
function.
console.time('doSomething')
for(let i = 0; i < SOME_BIG_NUMBER; i++) {
// do something
console.timeLog('doSomething');
}
console.timeEnd('doSomething')
Again, this function allows you to specify a label so you can refer to multiple timers.
It’s worth noting if you’re just using one timer, then you can use a default one by simply not providing a label argument to any of the above functions.
Alternatively use performance.now()
There is a another way to time functions and that is by using the performance
object which has now
function available.
const startTime = performance.now();
//do something
const endTime = performance.now();
console.log(`Took ${endTime - startTime} milliseconds`);
This gives pretty much the same result as using the console.time
functions so what’s the difference?
Well, according to MDN this should give us greater accuracy but really the difference is that the start and end dates will be relative to when the navigation to the particular page/tab the code is running in was opened.