Count functions calls with JavaScript

后端 未结 4 394
傲寒
傲寒 2021-01-21 12:16

For example: I have a lot of functions and use them many times. I need to count calls for each function. What is the best practice to make it?

At first i thought i need

4条回答
  •  日久生厌
    2021-01-21 12:39

    In the simplest case, you can decorate each function with a profiling wrapper:

    _calls = {}
    
    profile = function(fn) {
        return function() {
            _calls[fn.name] = (_calls[fn.name] || 0) + 1;
            return fn.apply(this, arguments);
        }
    }
    
    function foo() {
        bar()
        bar()
    }
    
    function bar() {
    }
    
    foo = profile(foo)
    bar = profile(bar)
    
    foo()
    foo()
    
    document.write("
    " + JSON.stringify(_calls,0,3));

    For serious debugging, you might be better off with a dedicated profiler (usually located in your browser's console).

提交回复
热议问题