Open In App

How to find out how many Times a Function is Called with JavaScript ?

Last Updated : 10 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, a function can be called multiple times wherever you need the same kind of functionality. You can also keep track of the function calls to find out how many times it is called in the whole code using the below approaches.

Using a Counter Variable

In this approach, a counter variable is used inside the function which will be incremented by one every time the function is called and the final value of the counter variable will be equal to the function calls.

Example: The below code implements the counter variable to find out the number of times a function is called.

JavaScript
let counter = 0;
function myFunction() {
    counter++;
}

// Calling the function
myFunction();
myFunction();
myFunction();
myFunction();
console.log("Function called:", 
    counter, "times");

Output
Function called: 4 times

Using a Wrapper Function

We can wrap the original function inside another function that increments a counter before calling the original function. Thus finding out how many times a function is called within JavaScript program.

Example: The below code uses a wrapper function to wrap the original function to count the number of times the function has been called.

JavaScript
let counter = 0;
function myFunctionWrapper() {
    counter++;
    myFunction(counter);
}

function myFunction(count) {
    console.log("Function called:", 
        count, "times");
}

myFunctionWrapper();
myFunctionWrapper();
myFunctionWrapper();

Output
Function called: 1 times
Function called: 2 times
Function called: 3 times

Using a Proxy Object

We use Proxy object to intercept calls to the original function and each time the function is called through the proxy, it logs the number of times the function has been called and thus counting the number of times the function has been called.

Example: The below code uses a proxy object to find out the number of times a function is called.

JavaScript
let counter = 0;
const myFunctionProxy = new Proxy(myFunction, {
    apply: function
        (target, thisArg, args) {
        counter++;
        return Reflect.apply
            (target, thisArg, args);
    }
});

function myFunction() {
    console.log("Function called:",
        counter, "times");
}

myFunctionProxy();
myFunctionProxy();
myFunctionProxy();
myFunctionProxy();

Output
Function called: 1 times
Function called: 2 times
Function called: 3 times
Function called: 4 times

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads