Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save levonlee/0e15eecab08283f5808a to your computer and use it in GitHub Desktop.
Save levonlee/0e15eecab08283f5808a to your computer and use it in GitHub Desktop.
AngularJS Chaining Promises for Unknown Amount of Times

How to chain promises one after another for unknown amount of times? This example shows how chain $timeout using .then()

Each $timeout change the color of a block in a random delay time.

And each one happens one by one for dynamic number of times.

.black {background-color:black; color: white;}
.red {color: red !important;}
.orange {color: orange !important;}
.tomato {color: tomato !important;}
.yellow {color: yellow !important;}
.blue {color:blue !important;}
.crimson {color: crimson !important;}
.indigo {color: indigo !important;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.js"></script>
<div ng-app="myapp" ng-controller="parentCtrl">
<div ng-class="[color,'black']">
Color: {{color}}
</div>
</div>
var app=angular.module('myapp',[]);
app.controller('parentCtrl',function($scope,$timeout) {
var maxCycle = 5; // Change color 5 times
$scope.color = '';
var styles = ['red','orange','tomato','yellow','blue','crimson','indigo'];
var styleIndex = 0;
var timeRange = [1,10]; // from 1 to 10 secs
function getRandomClass() {
var i = styleIndex;
if (styleIndex >= styles.length-1) {
i =0;
styleIndex = -1;
}
styleIndex++;
return styles[i];
}
function getRandomTime() {
return (Math.floor(Math.random()*timeRange[1])+timeRange[0])*1000;
}
$scope.blockOne = function() {
$scope.color = getRandomClass();
console.log('Change color to: ', $scope.color);
}
var changes = [];
for (var i=0; i<=maxCycle-1; i++) {
changes[i] = function() {
var delay = getRandomTime();
console.log('Entering change');
console.log('Delay:', delay);
return $timeout($scope.blockOne, delay);
}
}
var executeChanges;
for (var i=0; i<=changes.length; i++) {
if (i==0) {
executeChanges = changes[0]();
} else {
executeChanges = executeChanges.then(changes[i]);
}
}
});
normalize_css: no
panel_jss: 0
panel_css: 0
wrap: b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment