Q:

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!

A:

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.

