JavaScript does not have a built-in feature that tracks how many times a function has been called. If you need this information, you must store it in a persistent location such as a variable outside the function.
The best practice would be to use a dedicated variable outside the function for this purpose, but if that is not an option, you can store the information directly on the function itself. Since functions are objects, you can add properties to them:
function fn() {
fn.callCount = (fn.callCount || 0) + 1;
// ...
}
Within a function, its name is accessible and can be used to retrieve and update the value of a callCount
property, incrementing it each time the function is called.
This method will only track the number of times that particular function was called. In case your function is nested and you want to track the total calls to all instances of the function created by the parent function, you can store the information on the parent function instead:
function parent() {
function fn() {
parent.fnCallCount = (parent.fnCallCount.callCount || 0) + 1;
// ...
}
// ...
}
However, it's advisable to avoid this approach if possible and opt for using a separate variable.
For live examples and comparisons:
// JavaScript code snippets here
// CSS code snippets here
If you prefer using a variable (despite your initial preference against it), here is an alternative implementation:
// More JavaScript code snippets here
// Additional CSS code snippets here