Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  6] [ 3]  / answers: 1 / hits: 35067  / 12 Years ago, sun, march 25, 2012, 12:00:00
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

More From » javascript

 Answers
13

Assuming you have a function:



var foo = function() {
...
};


or if you prefer:



function foo() {
...
}


you could invoke it 5 times at intervals of 1 second like that:



(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);


And here's a live demo.


[#86617] Friday, March 23, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
claudia

Total Points: 734
Total Questions: 106
Total Answers: 113

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
;