运行指定次数的函数

yet*_*ker 8 javascript

function runAgain()
{
    window.setTimeout(foo, 100);
}

function foo()
{
    //Do somthing
    runAgain();
}
Run Code Online (Sandbox Code Playgroud)

我可以使用上面的代码以一秒的间隔无限次地运行一个函数.

运行函数定义次数的标准方法是什么.让我们说,我希望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
Run Code Online (Sandbox Code Playgroud)

gdo*_*ica 8

var counter = 1;
function foo()
{
    if (counter < 5){
        counter++
        window.setTimeout(foo, 1000);
    }
}

foo()// it will run 5 times;
Run Code Online (Sandbox Code Playgroud)

现场演示


带"静态变量"的版本:

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();
Run Code Online (Sandbox Code Playgroud)

现场演示


隐藏输入的版本

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();?
Run Code Online (Sandbox Code Playgroud)

现场演示


封闭版本:

var x = function() {
    var counter = 1;

    (function foo() {
        alert('Run No. ' + counter);

        if (counter < 5) {
            counter++;
            setTimeout(foo, 400);
        }
    })();
};
x();?
Run Code Online (Sandbox Code Playgroud)

现场演示


Dar*_*rov 6

假设你有一个功能:

var foo = function() {
    ...
};
Run Code Online (Sandbox Code Playgroud)

或者如果您愿意:

function foo() {
    ...
}
Run Code Online (Sandbox Code Playgroud)

你可以以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);
Run Code Online (Sandbox Code Playgroud)

这是一个现场演示.