Skip to content

Latest commit

 

History

History
48 lines (36 loc) · 1.55 KB

count-how-many-times-a-function-has-been-called.mdx

File metadata and controls

48 lines (36 loc) · 1.55 KB
category created tags title
Tip
2022-09-27
JavaScript
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