function runAgain()
{
window.setTimeout(foo, 100);
}
function foo()
{
//Do somthing
runAgain();
}
我可以使用上面的代码以1秒的间隔无限次地运行函数。
运行函数定义次数的标准方法是什么。可以说,我希望foo()
以1秒的间隔运行5次。
编辑据说在Javascript中应该避免使用全局变量。是不是有更好的方法?
根据答案的输入,我创建了一个这样的函数:(工作示例:http://jsbin.com/upasem/edit#javascript,html)
var foo = function() {
console.log(new Date().getTime());
};
var handler = function(count) {
var caller = arguments.callee;
//Infinite
if (count == -1) {
window.setTimeout(function() {
foo();
caller(count);
}, 1000);
}
if (count > 0) {
if (count == 0) return;
foo();
window.setTimeout(function() {
caller(count - 1);
}, 100);
}
if (count == null) {foo(); }
};
handler(-1); //Runs infinite number of times
handler(0); //Does nothing
handler(2); //Runs two times
handler(); //Runs foo() one time
答案 0 :(得分:8)
var counter = 1;
function foo()
{
if (counter < 5){
counter++
window.setTimeout(foo, 1000);
}
}
foo()// it will run 5 times;
function foo() {
if (typeof foo.counter == 'undefined') {
foo.counter = 0;
}
alert("Run No. " + (++foo.counter));
if (foo.counter < 5) {
setTimeout(function() {
foo(foo.counter + 1);
}, 400);
}
}
foo();
隐藏输入的版本
function foo() {
var counter = document.getElementById('counter');
var counterValue = parseInt(counter.value, 10);
alert('Run No. ' + counterValue);
if (counterValue< 5) {
counter.value = counterValue + 1;
window.setTimeout(foo, 400);
}
}
foo();
<强> LIVE DEMO 强>
带闭包的版本:
var x = function() {
var counter = 1;
(function foo() {
alert('Run No. ' + counter);
if (counter < 5) {
counter++;
setTimeout(foo, 400);
}
})();
};
x();
答案 1 :(得分:6)
假设你有一个功能:
var foo = function() {
...
};
或者如果您愿意:
function foo() {
...
}
你可以按照1秒的间隔调用它5次:
(function(count) {
if (count < 5) {
// call the function.
foo();
// The currently executing function which is an anonymous function.
var caller = arguments.callee;
window.setTimeout(function() {
// the caller and the count variables are
// captured in a closure as they are defined
// in the outside scope.
caller(count + 1);
}, 1000);
}
})(0);
这是一个live demo。
答案 2 :(得分:2)
为避免使用其他变量污染全局环境,可以将其包装在匿名函数中:
(function() {
var counter = 0;
function foo() {
// do stuff
if ((++counter) < 5) window.setTimeout(foo, 1000);
}
})();
答案 3 :(得分:1)
使用全局变量并在函数foo()中递增它以计算它被调用的次数。
var counter=0;
function runAgain()
{
window.setTimeout(foo, 1000);
}
function foo()
{
//Do somthing
if((++counter)<5)
runAgain();
}
答案 4 :(得分:0)
function call (func, arg) {
return {
func,
arg,
times: function (num) {
let counter = 0;
while (counter < num) {
this.func(this.arg);
counter += 1;
}
}
};
}
然后使用它,你可以做到
call(yourFunction).times(10)
或者,如果您需要输入参数:
call(yourFunction, arg).times(10)