how can i use $interval in for loop

411 views Asked by At

Hi i want to run $interval in the for loop

what i did

  • i implemented below code for auto refreshing
  • i am] checking data array with status queued object
  • then i am calling refresh instance (it is an ajax call to get the status of the instance)
  • but suppose if there are more than one instance having queued as a status then refreshing the instnace with last one

what i wnat i want to refresh all the isntnaces

ex:

data=[{id:1,status:'queued'},{id:2,status:'active'},{id:3,status:'queued'},{id:4,status:'active'},{id:5,status:'queued'}];

then id:5 instnace is only refreshing but i want all the instaces like 1,3,5

for (var i = 0; i < data.length; i++)
{   
  if(data[i].status =='queued')
  {
    var id = data[i].id;
    promiseObj[id] = $interval( function(){ $scope.refreshInstance('active',id); }, 20000);

  }
}
1

There are 1 answers

0
Arun P Johny On BEST ANSWER

The problem here is the use of a closure inside a loop.

But in this case you can fix it using a much easier forEach() loop

angular.forEach(data, function (item, idx) {
    if (item.status == 'queued') {            
        promiseObj[item.id] = $interval(function () {
            $scope.refreshInstance('active', item.id);
        }, 20000);
    }
});