How to use a Counter Variable In Javascript
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.
let counter = 0;
function myFunction() {
counter++;
}
// Calling the function
myFunction();
myFunction();
myFunction();
myFunction();
console.log("Function called:",
counter, "times");
Output
Function called: 4 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