young-ceo
young-ceo

Reputation: 5384

Execute method with Angular's $timeout in a for loop

I'm learning AngularJS.

What I want to do is execute a method in a for loop with $timeout.

Here is 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 variable 'i'. How can I achieve this? Also, I'd like to know how to solve this problem with Angular $interval() as well.

Thanks!

Upvotes: 3

Views: 6340

Answers (2)

Srinivas Paila
Srinivas Paila

Reputation: 827

Using $interval:

var i=0;
$interval(function(){
    someMethod(i++);
}, 1000, 10);


function someMethod(i) {
    console.log('Executed : ', i);
}

Using a self executing function as Dave said ($interval with a for loop): You can limit the iterations to 1 for all the calls as third parameter for $interval

for(var i = 0; i < 10; i++) {
    (function(i){  
        $interval(function(){
            someMethod(i);
        }, 1000, 1);
    })(i); 
}

Upvotes: 1

Dave Walker
Dave Walker

Reputation: 3523

You need to wrap it in a closure function, pass in the i variable, and then it will become available within the scope of that new function.. e.g.

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 around setTimeout for testability. So see http://jsfiddle.net/f1yfy6ac/3/ for this in action.

If you were wanting to use $interval instead then you could use:

$interval(someMethod, 1000) 

This would then pass in i anyway. You wouldn't need to use it in a loop.

Upvotes: 9

Related Questions