Count functions calls with JavaScript

2019-02-27 00:35发布

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 closures, but I can't implement it in a right way.

4条回答
beautiful°
2楼-- · 2019-02-27 00:43

You could try something like this:

<script>
    var aCalls = 0;
    var bCalls = 0;
    function a()
    {
        aCalls = aCalls + 1;
        alert(aCalls);
    }
    function b()
    {
        bCalls = bCalls + 1;
        alert(bCalls);
    }
</script>
查看更多
贼婆χ
3楼-- · 2019-02-27 00:52
var count = 0;

function myfunction()
{
    count++;
    alert( "Function called " + count);
}


myfunction();
myfunction();

http://jsfiddle.net/xsdzpmwm/3/

查看更多
小情绪 Triste *
4楼-- · 2019-02-27 00:57

The best way is to use a profiler.

On IE: press F12 to open developer tools, then go to the Profiler tab, and hit the play button. After stopping the profiler, you'll be presented with a lot of info (number of calls for each function, inclusive time, exclusive time, etc.)

On Chrome: press F12, go to Profiles, Collect JavaScript CPU Profile (that won't tell you the number of calls though)

查看更多
乱世女痞
5楼-- · 2019-02-27 01:01

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("<pre>" + JSON.stringify(_calls,0,3));

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

查看更多
登录 后发表回答