0

I want to use delay in my angular.foreach loop. I have a list and I want to display them one by one with 2 seconds periods.

 angular.forEach(vm.SimulationResult, function (value, key) {
                    timeout2 = $timeout(function () {
                        vm.Alerts.push({ msg: value.MainStatus });
                    }, 2000);
                });

what should I do ?

Frank van Wijk
  • 3,234
  • 20
  • 41
Egomen
  • 93
  • 3
  • 11

1 Answers1

5

Take advantage of the fact that $timeout returns a promise and chain the promises together so that each one starts another promise timeout that will push the next alert:

let promise = $timeout();
angular.forEach(vm.SimulationResult, function(value, key) {
     promise = promise.then(function() {
         vm.Alerts.push({ msg: value.MainStatus });
         return $timeout(2000);
     });
});

(make sure your version of angular is up to date as older versions didn't let you omit the callback function in a timeout)

Duncan
  • 92,073
  • 11
  • 122
  • 156