Execute method with Angular $ timeout in for loop
I am learning AngularJS.
What I want to do is execute the method in the for loop with $ timeout.
Here's an example:
for(var i = 0; i < 10; i++) {
$timeout(function(i) {
someMethod(i);
}, 1000);
}
function someMethod(i) {
console.log('Executed : ', i);
}
But I cannot pass the variable 'i'. How can I achieve this? Also, I would like to know how to solve this problem using Angular $ interval ().
Thank!
source to share
You need to wrap it in a closure function, pass it in a variable i, and then it becomes available within this new function ... for example.
for(var i = 0; i < 10; i++) {
(function(i){ // i will now become available for the someMethod to call
$timeout(function() {
someMethod(i);
}, i * 1000);
})(i); // Pass in i here
}
function someMethod(i) {
console.log('Executed : ', i);
}
Remember that $ timeout is just a wrapper for setTimeout to check. So see http://jsfiddle.net/f1yfy6ac/3/ for this in action.
If you want to use $ interval instead, you can use:
$interval(someMethod, 1000)
Then it will pass anyway. You won't need to use it in a loop.
source to share
Using the $ interval:
var i=0;
$interval(function(){
someMethod(i++);
}, 1000, 10);
function someMethod(i) {
console.log('Executed : ', i);
}
Using the self-emitting function as Dave said ($ interval with for loop): You can limit iterations to 1 for all calls as the third parameter to $ interval
for(var i = 0; i < 10; i++) {
(function(i){
$interval(function(){
someMethod(i);
}, 1000, 1);
})(i);
}
source to share