2

how to wait untill all AngularJS' $timeouts are done ?

for (var i = 0; i < 1000; i++) {
   $timeout(function () {
      //do sth
   }, 100);
};

//then do something else is all $timeouts are done
Tony
  • 12,405
  • 36
  • 126
  • 226
  • I can't think of a native solution to this, but it's very easy to implement some sort of an async manager, where every call to a start method (called when you set a timer) increases a counter, and every call a stop method (called when an async function finishes) decreases it. The final callback can be triggered when the counter is back to 0. – doldt Nov 28 '14 at 15:15

1 Answers1

3

You could use the promises returned by the timeouts and with the combination of $q.all (inject $q) you could achieve that.

Example:-

var promises = [];

for (var i = 0; i < 1000; i++) {
  promises.push(performTask(i)); //push promise to the array
}


//If in your real case i is actually an array of something then you can 
//just simplify it to $q.all(myArrayOfInputs.map(performTask)).then(...)

$q.all(promises).then(performDoneTask); //use q.all to wait for all promises to be fulfilled.

//Method that does something once all the timeouts are completed
function performDoneTask(){

}

//Method that does something with i and returns a promise from the timeout
function performTask(i){ 
  return $timeout(function () {
      //do sth
   }, 100);
}
PSL
  • 123,204
  • 21
  • 253
  • 243
  • Hmmm thanks for that - till now i was creating custom promise (with $q) and wraps all others inside it with notices and so on - this is also nice how ever for some of my purposes wrapperpromise is better. Anyway thanks. – Seti Nov 28 '14 at 15:26
  • @seti Doing custom promise you mean creating deferred object with $q? WHich you do not have to (unless there is really no other option) because timeout already returns a promise. Read this http://stackoverflow.com/questions/23803743/what-is-the-deferred-antipattern-and-how-do-i-avoid-it – PSL Nov 28 '14 at 15:29
  • Yes, defered with $q. – Seti Dec 11 '14 at 15:40