/frontend-tips GitHub 486★

Count how many times a function has been called

If you want to count how many times a function has been called, you probably think of a global variable:

let counter = 0;

const expensiveFunctionToDebug = () => {
counter++;
console.log(`This function has been called: ${counter}`);

// Function body ...
};

We simply increase the counter by 1 and log the latest value whenever the expensiveFunctionToDebug function is invoked. console has a great method to do the same thing:

const expensiveFunctionToDebug = () => {
console.count('expensiveFunctionToDebug');

// Function body ...
};

In the Console tab of browsers, you will see something as following:

expensiveFunctionToDebug: 1
expensiveFunctionToDebug: 2
...
expensiveFunctionToDebug: 10

The console.count function prints the label you pass to it followed by the number of times the function is executed.

See also

Follow me on and to get more useful contents.