Nagaveer Gowda Nagaveer Gowda - 10 days ago 6
AngularJS Question

Angularjs : Update a variable after some time

I'm trying to show some text while getting data from the server.
I'm trying to update the variable to show loading messages after some fixed time. But I'm unable to do.

<div class="circularProgress" ng-if="showCircularProgress" id="circularProgress">
<md-progress-circular md-mode="indeterminate" md-diameter="70"></md-progress-circular>
<span>{{progressMessage}}</span>
</div>

angular.forEach(messageArray, function(msg, i) {
setTimeout(updateProgressMessage(msg), 1000);
});

var updateProgressMessage = function(message){
$scope.progressMessage=message;
}


Could anyone suggest me in setting delay?

Answer

You'll have to use $timeout so that angular knows to run a digest after the callback is called. You'll also need to wrap updateProgressMessage(msg) in an anonymous function so that it doesn't get called immediately.

angular.forEach(messageArray, function(msg, i) {
    $setTimeout(function() { updateProgressMessage(msg); }, 1000);
});

If you want to repeatedly call updateProgressMessage use $interval instead and your callback will be invoked at regular intervals

For further information see the docs for $interval and $timeout

Update

If messageArray contains several items e.g. var messageArray = [1,2,3,4,5] then the above code will create a timeout for each item that will each fire at roughly the same time after about 1 second.

I'm not sure this is the behaviour you're after and would have thought you'd want something like this.

var messageArray = [1,2,3,4,5];

var intervalPromise = null;

intervalPromise = $setInterval(function() {
    if (messageArray.length > 1){
        // remove an item from the messageArray and update the progress message  
        updateProgressMessage(messageArray.shift()); 
    } else {
        // no more update messages
        $interval.cancel(intervalPromise);
    }
}, 1000);

var updateProgressMessage = function(message){
    $scope.progressMessage = message;
};

This will create an interval and fire every second (approximately). Once all messages have been processed the interval is cancelled to prevent any further execution.

Comments