3

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!

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks for replying! But I'm expecting that someMethod() calls each second - how can I do that?
For example, console like: 'Executed : 1' (after 1 second) 'Executed :2' (after 1 second) ...
Ok updated it so that it'll work. But there are several ways you can achieve this better. I'd suggest using docs.angularjs.org/api/ng/service/$interval
$interval is by far the best solution. You don't need a for loop for one you just call it. If you want to limit the number of iterations then that's the third argument. E.g. $interval(someMethod, 1000, 10)
So interval will just pump for every timespan you give it. If you used it in a for loop then you'd create multiple pumps. So after one second your function would call once, after two it would be called twice, after three it would be called three times... Make sense?
|
1

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

1 Comment

Thanks! but I want to use it with a for loop! Do you have better approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.