如何找出使用 javascript/jquery 调用函数的次数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8517562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find out how many times a function is called with javascript/jquery?
提问by Weblurk
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?
那么,我如何找出上面代码中的 X 呢?
回答by Vilx-
Easy version: make a global variable like in codeling's answer. The problem - if some other code also defines a global variable with the same name, you're both in trouble.
简单版本:创建一个全局变量,就像在codeling's answer 中一样。问题 - 如果其他一些代码也定义了一个同名的全局变量,那么你们都有麻烦了。
Easy extended version - give the variable a crazy name that nobody will ever use: calledTimesED7E69A7B141457CA8908A612E3D7A3A
简单的扩展版本 - 给变量一个没人会使用的疯狂名称: calledTimesED7E69A7B141457CA8908A612E3D7A3A
Clever version: append that variable to an existing global variable. Remember - everything'san object in Javascript!
聪明的版本:将该变量附加到现有的全局变量。请记住 -在 Javascript 中一切都是对象!
$(function(){ setInterval(myFunction, 3000); });
function myFunction()
{
myFunction.calledTimes++;
alert( "I have been called " + myFunction.calledTimes + " times" );
}
myFunction.calledTimes = 0;
Traditional version: use scoping to hide that variable.
传统版本:使用作用域来隐藏该变量。
$(function()
{
calledTimes = 0;
setInterval(function()
{
calledTimes++;
alert( "I have been called " + calledTimes + " times" );
}, 3000);
});
This hides "myFunction" though, so let's try again with a tricky kind of scoping:
这虽然隐藏了“myFunction”,所以让我们用一种棘手的范围界定再试一次:
var myFunction = null;
(function()
{
calledTimes = 0;
myFunction = function()
{
calledTimes++;
alert( "I have been called " + calledTimes + " times" );
}
})();
$(function () { setInterval(myFunction, 3000); });
... and there are a zillion other ways you would hide that variable with scoping. Just pick your favorite.
...还有无数其他方式可以通过作用域来隐藏该变量。选择你最喜欢的。
回答by codeling
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).
一旦您的代码变得有点复杂(或者如果您使用了很多其他库),您就应该考虑使用范围界定,如此处的其他答案所示(最好在Vilx 的那个答案中进行了解释)。
回答by ma?ek
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 unobtrusivecounter 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
setInterval
输出
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
回答by Ben West
You'll have to use a closure. Normally you would use a static variable. in Javascript it would look something like:
你必须使用闭包。通常你会使用静态变量。在 Javascript 中,它看起来像:
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/
回答by aljgom
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 */ }
回答by Dhinakar
Create a global variable and initialize by zero. then increment by one when myfunction() called. Display that variable instead of X.
创建一个全局变量并初始化为零。然后在调用 myfunction() 时加一。显示该变量而不是X。