$interval Service:
AngularJS includes $interval service which performs the same task as setInterval() method in JavaScript. The $interval is a wrapper for setInterval() method, so that it will be easy to override, remove or mocked for testing.
The $interval service executes the specified function on every specified milliseconds duration.
Signature: $interval(fn, delay, [count], [invokeApply], [Pass]);
The following example demonstrates $interval service that displays a counter on each 1000 milliseconds.
Example: $interval
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
{{counter}}
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($scope, $interval) {
$scope.counter = 0;
var increaseCounter = function () {
$scope.counter = $scope.counter + 1;
}
$interval(increaseCounter, 1000);
});
</script>
</body>
</html>
In the above example, $interval service calls increaseCounter() function on every 1000 milliseconds. The increaseCounter() function increases the $scope.counter property by 1. Thus, counter increases on every milliseconds.
Specify count:
The $interval service also executes the specified function for the specified number of times as count parameter.
Example: $interval
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
{{counter}}
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($scope, $interval) {
$scope.counter = 0;
var increaseCounter = function () {
$scope.counter = $scope.counter + 1;
}
$interval(increaseCounter, 1000, 10);
});
</script>
</body>
</html>
In the above example, increaseCounter() method will be executed on each 1000 milliseconds but not more than 10 times.
Cancel execution:
The $interval service returns an object of HttpPromise which can be used to stop the counter by using $interval.cancel(promise) method.
Example: $interval.cancel()
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
<div>
<div ng-controller="myController">
{{counter}} <br /><br />
<button ng-click="cancel()">Cancel</button>
</div>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($scope, $interval) {
$scope.counter = 0;
var increaseCounter = function () {
$scope.counter = $scope.counter + 1;
}
var promise = $interval(increaseCounter, 1000);
$scope.cancel = function () {
$interval.cancel(promise);
$scope.counter = "Cancelled!";
};
});
</script>
</body>
</html>