Better debug your code with console.timer()

Better debug your code with console.timer()

ยท

2 min read

Hello good people! In this article, I want to shed light on a very interesting console function. It's called console.timer() and might help you understand how your code runs and optimize it.

This will be a rather short article. We'll go through two simple examples to understand how it works and hopefully get you started.

How console.timer() works โŒš

Let's get straight to the point with a simple code snippet. We'll declare an array and fill it with some values as below.

console.time('mylabel');

let arr = [];

for (let i = 0; i < 100000; i++) {
  arr[i] = (i + 1) * 100;
}

console.timeEnd('mylabel');

As you can see, I've surrounded the snippet with console.time('label') and console.timeEnd('mylabel'). Running this on NodeJS or your browser's console will output a line as follows :

mylabel: 4.125 ms

image.png

So what happened? ๐Ÿง

Imagine you have a stopwatch, you'll tap the start button once it reaches the console.time() and you'll tap the stop button once it reaches the console.timeEnd(). This exactly what the JavaScript runtime is doing, just instead of you fiddling with a stopwatch it does it for you ๐Ÿ˜ !

The mylabel is just a way to help us use "multiple stopwatches". Your label needs to match a start and an end to work properly so be mindful about that.

Multiple timings with console.timeLog() โณ

Let's make our example more interesting with another for loop and try to use console.timeLog() with it:

console.time('mylabel');

let arr = [];

for (let i = 0; i < 100000; i++) {
  arr[i] = (i + 1) * 100;
}

console.timeLog('mylabel');

let arr2 = [];

for (let i = 0; i < 100000; i++) {
    arr2.push((arr[i] * Math.PI) / 1.33);
}

console.timeEnd('mylabel');

If you run again this code, you'll have an input roughly like the following:

mylabel: 4.179ms
mylabel: 11.824ms

As you can see, now we have an intermediary output. This is awesome because you can use the same label to keep track of the timings of each block of code as you like.

Wrap-up ๐Ÿ“ฆ

And that's it! Using console.time() is really straightforward. I used it two days ago to find out which loop was taking too much time to run and thus impact our client's app performance.

I really hope you like this shorter format. In any case, I'll be pleased to read your feedback.

Cheers!

Photo by @jontyson from Unsplash.com.

Did you find this article valuable?

Support Tarek Jellali by becoming a sponsor. Any amount is appreciated!

ย