Cancelling a $timeout
Demonstrates how to cancel a previously started $timeout function.
HTML
<div ng-app>
<div ng-controller="Ctrl">
<h1>{{greeting}} {{yourName}}!</h1>
<button ng-click="updateName()">Say Hello to people</button>
<button ng-click="stopit()">Stop doing that</buttton>
</div>
</div>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
<style>
JavaScript
function Ctrl($scope,$timeout) {
var names = ['igor','misko','vojta','adam'],
prom, lngth = names.length, ctr = 0;
$scope.greeting = "Hello";
$scope.updateName = function() {
ctr = ctr + 1;
var idx = ctr % lngth;
$scope.yourName = names[idx];
prom = $timeout($scope.updateName, 1000);
};
$scope.stopit = function() {
$scope.greeting = "Goodbye";
console.log($timeout.cancel(prom);)
};
}