How to use a Wrapper Function In Javascript
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.
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
How to find out how many Times a Function is Called with JavaScript ?
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.
Table of Content
- Using a Counter Variable
- Using a Wrapper Function
- Using a Proxy Object