Home

1 minute read

Timing Functionality in JavaScript

Tony Lea

Timing Functionality in JavaScript

Timing the functionality in your JavaScript code can help you write more efficient code and it can help you figure out which code is slowing down your application.

Luckily JavaScript has a few handy helper functions we can utilize to test the speed of our functionality. These functions are console.time() and console.timeEnd() which can be used like this:

console.time();

for(i=0; i<1000000; i++){
    // Logic Here
}

console.timeEnd();

If you wish to have multiple timers in your code it’s best to give your timer a label like so:

// Run Some Functionality
console.time('Functionality #1');

for(i=0; i<1000000; i++){
    var func1Value = i+i;
}

console.timeEnd('Functionality #1');


// Run Another Type of Functionality
console.time('Functionality #2');

for(i=0; i<1000000; i++){
    var func2Value = (i*i)+(2*i);
}

console.timeEnd('Functionality #2');

Now when you run your code in the browser and you open up the developer console you’ll see an output that will give you the time it took to execute each piece of functionality.

These timers can help you make your application more efficient and make the user experience better.