I want to find out how many times a particular JavaScript function has been called in an HTML file with dev tools but couldn't figure out how and couldn't find anything through Googling, any pointer is appreciated
thank you in advance
You can use code instrumentation (or monkey patching) to track the number of times a function gets invoked, as well as many other things.
Take a simple function:
function foo () {
console.log('bar');
}
We can patch the function to keep track of the invokation count. Instead of polluting the global scope with counts for every function that gets patched, we can keep the count on the function itself. This is possible because everything in JavaScript is an object.
var oldFoo = foo;
foo = function () {
++foo.count;
return oldFoo.apply(this, arguments);
}
foo.count = 0;
Now if we invoke foo
, we will be able to access the count at foo.count
. The problem here is that it takes three bits of code to achieve this. The first is keeping track of the old function, the second is redefining it, and the last is setting the original count to 0.
We can improve this by creating a generic patchMyFunc
function that takes in the function name as a string, and then modifies the actual function given the context that the patch function was run in. In global scope, the context would be window
in a browser.
function patchMyFunc (funcName) {
var context = this;
var oldFunc = context[funcName];
context[funcName] = function() {
++context[funcName].count;
return oldFunc.apply(context, arguments)
}
context[funcName].count = 0;
}
Now we just have to invoke the patch function with our function name and we're good.
patchMyFunc('foo');