Run a function a specified number of times
<pre><code>function runAgain()
{
    window.setTimeout(foo, 100);
}

function foo()
{
    //Do somthing
    runAgain();
}
</code></pre>

<p>I can use the above code to run a function infinite number of times with an interval of one second.</p>

<p>What is the standard way of running a function defined number of times. Lets say, I want <code>foo()</code> to be run 5 times with an interval of 1 second.</p>

<p><strong>EDIT</strong> It's said that global variables should be avoided in Javascript. Isn't there a better way?</p>

<p>With input from answers, I created a function like this:  (Working Example: <a href="http://jsbin.com/upasem/edit#javascript,html" rel="nofollow">http://jsbin.com/upasem/edit#javascript,html</a> )</p>

<pre><code>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 &gt; 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
</code></pre>
