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

后端 未结 6 618
心在旅途
心在旅途 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:04

    A static variable is cleaner and it won't pollute your outer scope either, compared to a closure or a decorator as in other answers.

    var foo = function(){
        alert( ++foo.count || (foo.count = 1) );
    }
    
    
    // test
    function callTwice(f){ f(); f(); }
    callTwice(foo)                  // will alert 1 then 2
    

    or

    callTwice( function bar(){           
        alert( ++bar.count || (bar.count = 1) );
    });                             // will alert 1 then 2
    

    the second one is a named anonymous function. And note this syntax:

    var foo = function bar(){ /* foo === bar in here */ }
    

提交回复
热议问题