Search code examples
angularjsangularjs-ng-repeat

How to display set of items in array after after some delay?


I am working on a chat application. I am getting all the chat history at once from an api and storing it in an array name $scope.channel I am displaying these list of items present in an array using ng-repeat. What I want to do is display sets of data from array in some intervals. For example when user opens chat screen he/she should be able to see few chats/images. Then after some seconds mmore data will be loaded.


Solution

  • As @Sajjad Shahi suggested you could use the $timeout service. Maybe something like the following. You can set the desired delay and chuck size. Use your $scope.channel array as srcArray and an empty array yourArrayToDisplay as destArray. Replace channel by yourArrayToDisplay in the ng-repeat directive. This should give you the desired result as far as I can follow.

    var dalayedChunkHandler =  {
        chunkSize: 1,
        delay: 2000,
        timeout: null,
        srcArray: [],
        destArray: [],
        dalayedChunk: function(){
            var _this = this;
    
            var len = _this.destArray.length;
            Array.prototype.push.apply(_this.destArray,_this.srcArray.slice(len, len + _this.chunkSize));                    
    
            if(_this.srcArray.length > _this.destArray.length) _this.start();
        },
        start: function(){
            var _this = this;
            _this.timeout = $timeout(function(){_this.dalayedChunk.call(_this)}, _this.delay)
        }
    };
    
    
    $scope.yourArrayToDisplay = []; // use this array for ng-repeat
    dalayedChunkHandler.destArray = $scope.yourArrayToDisplay;
    dalayedChunkHandler.srcArray = $scope.chatHistoryArray; // the array you got
    dalayedChunkHandler.start();