Skip to content

Instantly share code, notes, and snippets.

@bbraithwaite
Created June 14, 2015 23:48
Show Gist options
  • Save bbraithwaite/7ff06f9930cef20d9ec6 to your computer and use it in GitHub Desktop.
Save bbraithwaite/7ff06f9930cef20d9ec6 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Interval Example - Ticker and Promises</title>
<script type="text/javascript" src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>
</head>
<body ng-app="calculatorApp">
<div ng-controller="CalculatorController">
Ticker: {{ticker}}
<br><br>
<label>From:</label>
<input type="number" ng-model="from">
<label>Inc:</label>
<input type="number" ng-model="inc">
<input type="button" value="Start" ng-click="start()">
<input type="button" value="Cancel" ng-click="cancel()">
<h4>Debug Output</h4>
<div>{{debug}}</div>
</div>
<script type="text/javascript">
var app = angular.module('calculatorApp', []);
app.controller('CalculatorController', function calculatorController($scope, $interval) {
var counterInstance;
var counterFunction = function(start, inc) {
if ($scope.ticker === 0 && start)
$scope.ticker = start;
if (!inc)
inc = 1;
$scope.ticker += inc;
}
var debugOutput = function(msg) {
// logging for demo
$scope.debug += msg + ' * ';
}
// defaults
$scope.ticker = 0;
$scope.from = 0;
$scope.inc = 1;
$scope.start = function() {
$scope.debug = '';
counterInstance = $interval(counterFunction, 500, 3, true, $scope.from, $scope.inc);
debugOutput('Starting status: ' + counterInstance.$$state.status);
counterInstance.then(function(successCallback, errorCallback, notifyCallback) {
debugOutput('The interval was executed: ' + successCallback + ' times!');
debugOutput('Then status: ' + counterInstance.$$state.status);
// errorCallback (always undefined for interval)
// notifyCallback (always undefined for interval)
});
counterInstance.catch(function(errorCallback) {
// called when the interval is cancelled
if (errorCallback === 'canceled') {
debugOutput('The interval was cancelled!');
} else {
debugOutput('Something else went wrong!');
}
debugOutput('Catch status: ' + counterInstance.$$state.status);
});
counterInstance.finally(function() {
// always called regardless
// Status values:
// 0 for running
// 1 for done
// 2 for cancelled
debugOutput('Finally status: ' + counterInstance.$$state.status);
counterInstance = undefined;
});
}
$scope.cancel = function() {
if (angular.isDefined(counterInstance)) {
$interval.cancel(counterInstance);
}
}
$scope.$on('$destroy', function() {
$scope.cancel();
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment