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

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

    You'll have to use a closure. Normally you would use a static variable. in Javascript it would look something like:

    jQuery( document ).ready( function(){
        setInterval( myFunction, 3000 );
    });
    
    var myFunction = (function(){
        var count = 0;
        return function(){
             count++
             alert( "I have been called " + count + " times");
        }
    })();
    

    Demonstration: http://jsfiddle.net/MZQ83/2/

提交回复
热议问题