$interval

Course- AngularJS >

The $interval service is similar in function to the $timeout service, except it schedules a function for repeated execution with a time interval in between.

Injecting $interval

To use the $interval service you must have it injected into a controller function. Here is an example that injects the $interval service into a controller function:

var myapp = angular.module("myapp", []);

myapp.controller("MyController", function($scope, $interval){

});

As you can see, it is very similar to how you inject any other service in AngularJS.

Scheduling a Repeated Function Call

Once the $interval service is injected into your controller function, you can use it to schedule repeated function calls. Here is an example that used the $interval service to schedule a function call every 5 seconds:

var myapp = angular.module("myapp", []);

myapp.controller("MyController", function($scope, $interval){

    $interval(callAtInterval, 5000);

});

function callAtInterval() {
    console.log("Interval occurred");
}

This example schedules a function call to callAtInterval() every 5 seconds (5000 milliseconds).

If you want to call a function on the $scope object instead, you can do so like this:

var myapp = angular.module("myapp", []);

myapp.controller("DIController", function($scope, $interval){

    $scope.callAtInterval = function() {
        console.log("$scope.callAtInterval - Interval occurred");
    }

    $interval( function(){ $scope.callAtInterval(); }, 3000);
});

The function passed to the $interval service calls the callAtInterval() function on the $scope object.