Search code examples
angularjssettimeoutinfinite-loop

Never ending loop through array in AngularJS + setTimeout after each iteration


How can I achieve a never ending loop in AngularJS?

my try:

item_list = [{'id':1, 'photo':'path/src'}, {'id':2, 'photo':'path/src'}, {'id':3, 'photo':'path/src'}];

item_list.map(function(item) {
    setTimeout( function () {
         setCoverImage(item.photo);
    }, 5000);
)

I'm going to change cover image using setCoverImage() every 5 s using data from item_list.


Solution

  • First you should use AngularJS's $interval. Then simply increment a counter and use it to access the current element's photo property in your controller and use ng-src to reflect that URL in your img tag.

    <img ng-src="{{myCtrl.item_list[myCtrl.currentIndex].photo}}">
    

    Be careful that you never assign to the counter a value that would not correspond to an element in your array.

    if ((that.currentIndex + 1) >= that.item_list.length)
    

    See full example below

    angular.module('appModule', []).controller('MyController', ['$scope', '$interval', function($scope, $interval) {
      this.item_list = [{
        'id': 1,
        'photo': 'https://i.pinimg.com/736x/32/76/a2/3276a2111c65b2131ef834736f47162b--birthday-kitten-birthday-hats.jpg'
      }, {
        'id': 2,
        'photo': 'http://img.playbuzz.com/image/upload/f_auto,fl_lossy,q_auto/cdn/154cb38e-55e3-4294-bffe-6906b6a41a6b/c33bcc8b-40be-49c9-bad1-ee85f8275189.jpg'
      }, {
        'id': 3,
        'photo': 'http://4.bp.blogspot.com/-J4ioK5aRks8/Tx8d9D5K54I/AAAAAAAAABM/iTL4sbsNYmc/w1200-h630-p-k-no-nu/Surprised+and+serious+kitten.jpg'
      }];
      var that = this;
      this.currentIndex = 0;
      $interval(function() {
        if ((that.currentIndex + 1) >= that.item_list.length) {
          that.currentIndex = 0;
        } else {
          that.currentIndex++;
        }
      }, 5000);
    }])
    
    angular.bootstrap(window.document, ['appModule'], {
      strictDi: true
    });
    <div ng-controller="MyController as myCtrl">
      <img ng-src="{{myCtrl.item_list[myCtrl.currentIndex].photo}}">
    </div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>