function runAgain()
{
window.setTimeout(foo, 100);
}
function foo()
{
//Do somthing
runAgain();
}
I can use the above code to run a function infinite number of times with an interval of one second.
What is the standard way of running a function defined number of times. Lets say, I want foo()
to be run 5 times with an interval of 1 second.
EDIT It's said that global variables should be avoided in Javascript. Isn't there a better way?
With input from answers, I created a function like this: (Working Example: 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
var counter = 1;
function foo()
{
if (counter < 5){
counter++
window.setTimeout(foo, 1000);
}
}
foo()// it will run 5 times;
LIVE DEMO
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();
LIVE DEMO
Version with hidden input
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
Version with closure :
var x = function() {
var counter = 1;
(function foo() {
alert('Run No. ' + counter);
if (counter < 5) {
counter++;
setTimeout(foo, 400);
}
})();
};
x();
LIVE DEMO
use a global variable and increment it in the function foo() to count the number of times it has been called.
var counter=0;
function runAgain()
{
window.setTimeout(foo, 1000);
}
function foo()
{
//Do somthing
if((++counter)<5)
runAgain();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With