If you are experiencing delays in the execution of your SuiteScript or JavaScript, it can be tricky to troubleshoot exactly where things are going wrong. Fortunately for us, there is a timer feature built into JavaScript that we can use to track how much time has elapsed between two arbitrary points. In combination with events, it becomes relatively trivial to test things like service controller methods.

There are two useful methods attached to the console object called time() and timeEnd(). You can pass in a string which will name the timer. The idea is that at the start of the execution of code, you drop in a command to start a timer, and then, at the end, you tell it to stop. The elapsed time is that logged to the console. With this information, you get some useful diagnostic information that you can then use to troubleshoot potential problem areas.

Simple Demonstration

We will explore a more detailed example, but for now we will look at how you would use it.

console.time('My timer');
myProblematicFunction();
console.timeEnd('My timer');
> My timer: 5000.083740234375ms

In this example, I have a function called myProblematicFunction() that I suspect is taking a long time to execute. Therefore, to test this, I can add calls to the timer function before and after I call it. When the function completes, the time is logged to the console.

If you’re working with your own code, then it’s straightforward to use the above code before and after some code is executed. However, if you’re dealing with big operations, then you will need to find a way to hook into the code.

If you’re using SuiteCommerce Advanced, then you can temporarily edit the source files and wrap certain functions in a timer.

However, if you don’t have access to the code, then you can rely on events.

Example Using Extensibility API

With both the extensibility API and service controllers supporting events that fire at the beginning and ending of a method, you can bind the console.time() and console.timeEnd() callbacks using those hooks.

Let’s assume, for example, you want to test how long it takes to add an item to the cart. Using the extensibility API, you can hook in code that fires when the call to add an item first fires, and then when it completes.

var Cart = container.getComponent('Cart')

Cart.cancelableOn('beforeAddLine', function () {console.time('beforeAddLine')});
Cart.cancelableOn('afterAddLine', function () {console.timeEnd('beforeAddLine')});

If, after running this code, you add an item to the cart, you will get the following message in your developer console:

beforeAddLine: 1342.19189453125ms

Hopefully your timer is as low as mine.

Note that you may get an error that says Timer 'beforeAddLine' does not exist in addition to your timer, if you have more than one item in your cart. This is because the afterAddLine event fires for every item in the cart.

This method can be used with any of the events exposed by the extensibility API .