Weblurk Weblurk - 3 months ago 8
Javascript Question

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

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 function has been called. A simplified version of the problem:

jQuery( document ).ready( function(){
setInterval( "myFunction()", 3000 );
});

function myFunction()
{
alert( "I have been called X times" );
}


So, how do I figure out the X in the above code?

Answer

You could simply use a global variable, which is increased each time you call the function:

var myFuncCalls = 0;

function myFunction()
{
    myFuncCalls++;
    alert( "I have been called " + myFuncCalls + " times" );
}

As soon as your code gets a little more complex (or if you use a lot of other libraries), you should, however, consider using scoping as shown in the other answers here (best explained in the one by Vilx).