How do I find out how many times a function is called with javascript/jquery?

后端 未结 6 622
心在旅途
心在旅途 2020-12-09 04:32

Perhaps an odd question but here it goes: I have a function which I call periodically and within that function I need to know which iteration I\'m in, or how many times the

6条回答
  •  悲&欢浪女
    2020-12-09 05:02

    Here's another interesting solution that doesn't use an external variable. The best part about this is you can leave any pre-existing functions untouched and call them as you would normally. That means if you're attempting to "tap in" to an function in an existing library, this will work very well for you. It adds an unobtrusive counter and allows you to continue calling existing functions normally; even with arguments!

    // no js library required
    
    // pre-existing function
    var a = function(){
        console.log("pre-existing function function");
        console.log("arguments:", arguments);
    };
    
    // add counter func
    var addFnCounter = function(target){
        var swap = target;
        var count = 0;
        return function(){
            swap.apply(null, arguments);
            count++;
            console.log("func has been called " + count + " times");
            console.log("\n");
        };
    };
    
    // usage
    a = addFnCounter(a);
    
    // call a() as you would normally
    a();
    a(1,2,3);
    a('hello', 'world');
    
    // using your setInterval example
    setInterval(a, 3000);
    

    Output

    pre-existing function function
    arguments: []
    func has been called 1 times
    
    pre-existing function function
    arguments: [1, 2, 3]
    func has been called 2 times
    
    pre-existing function function
    arguments: ["hello", "world"]
    func has been called 3 times
    

    setInterval output

    pre-existing function function
    arguments: []
    func has been called 4 times
    
    pre-existing function function
    arguments: []
    func has been called 5 times
    
    pre-existing function function
    arguments: []
    func has been called 6 times
    

    See it working here on jsfiddle

提交回复
热议问题