How to use a Proxy Object In Javascript
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.
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
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