如何找出使用javascript/jquery调用函数的次数? [英] 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" );
}
那么,如何找出上面代码中的X?
So, how do I figure out the X in the above code?
推荐答案
您可以简单地使用一个全局变量,该变量在每次调用该函数时都会增加:
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" );
}
一旦您的代码变得更加复杂(或者如果您使用许多其他库),则应该考虑使用范围,如此处其他答案所示(Vilx的一本).
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).
这篇关于如何找出使用javascript/jquery调用函数的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!