Skip to content

Count events with the Browser Performance API

Published: at 06:00 PM

Welcome to the first post of the quick tips series, here I will share quick tips that can help you in your day-to-day work because they already helped me.

Table of Contents

Open Table of Contents

The problem I had

I need to count how many times a private function was called during the invocation of a public function. At the same time I want to keep track of the time it took to execute the public function. Last but not least, I cannot use flamegraphs of the browser’s devtools because the function is called multiple times in a short period of time.

I could use console.log but it would be a lot of noise in the console and I would have to count the logs manually or deeply change the code to count the invocations.

The solution I found

Performance API to the rescue!

Performance API

Modern problems require modern solutions APIs. The Performance API is a set of APIs that allow you to measure the performance of your web application. It provides a way to measure the time it takes to execute a function, the time it takes to load a resource, and much more.

One of the most useful functions I used is: performance.mark. It really simple as it just requires a name to mark the time.

performance.mark("mark-name");

This operation create a mark that can be used subsequently to measure time performances and aggregate stats.

In my case, I used it to count the number of times a function was called and the time it took to execute the function.

performance.getEntriesByName("mark-name").length;

At this point you could ask me: “where is the power of this API?“. The power of this API is that the pieces of code I showed you can be used in any part of your code! Even in different files!

Code

// a.js
function publicFunction() {
  const start = performance.now();
  ...
  // privateFunction is called multiple times, depending on data
  ...
  const end = performance.now();
  console.log(`Sorting took ${end - start}ms`);
  console.log('privateFunction called #', performance.getEntriesByName('mark-name').length, ' times.');
}

// b.js
function privateFunction() {
  performance.mark('mark-name');
  ...
}

It works very well and allow to quickly check performances without deeply change your code. Have you ever tried that API?