Find the time taken by a function in JavaScript

Photo by Lukas Blazek on Unsplash

Hello World !!!
There are numerous scenarios when we want to know the time taken by a function in JS but most of the time it is related to finding the one line of code which is taking ages to execute.

Here is the most common way of finding the time taken by a function JS:

Step 1: We create a variable on the top of the function, and store date in it. const startTime = new Date()

Step 2: Right before the end of the function, we subtract it from the current date to get time taken by the function in milliseconds.
console.log('Time Taken', new Date() — startTime)

Problem with Above method:

If we have to find the time multiple times within a function then we have to write console.log('Time Taken', new Date() — startTime) this line multiple times. Which becomes hard to manage when we have a long function.

To solve this, we can use console.time() . Which is more cleaner way of finding time taken by any function or code.

Few pointers on console.time().
0. First console.time()won’t print anything on the console. It will simply start the timer.
1. It takes a string as an argument, which act as a unique identifier for the timer.
2. We can have as many as console.time() with different unique identifiers.
3. Whenever we have to check the time, we simply have to add console.timeLog(uniqueIdentifier)
4. Every time we write console.timeLog() with identifier, it will show us the time took to reach to that line.
5. If we want to end our timer function. Simply write console.timeEnd(uniqueIdentifier) , and don’t forget to pass the unique identifier.

Example:

Output of above lines of Code is something like this:

I hope this made you to learn something new.

🍻

Happy Coding.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store