It is not always required of our functions to provide immediate results, sometimes we need to delay the changes made by a function, for eg, processing of an AJAX request or if we want to schedule changes to an animation. To such end AngularJS provides us with $timeout( ) and $interval( ) services.
To use these services, as usual, we have to inject the dependency into the controller
var myapp = angular.module("myapp", []);
myapp.controller("MyController", ['$scope','$timeout',function($scope, $timeout){
}]);
The $timeout service can be used to call another JavaScript function after a given time delay. The $timeout service only schedules a single call to the function. To invoke a function repeatedly we have to use the $interval( ) service. Both these services work in a similar manner, barring this functionality.
Once the $timeout service is injected into your controller function, you can use it to schedule function calls. For example:
myapp.controller("MyController", ['$scope','$timeout',function($scope, $timeout){
$timeout(callThis,2000);
}]);
function callThis(){
console.log("I am called after 2 seconds");
}
Here the time is to be entered in milliseconds. We can also call functions on the $scope object:
myapp.controller("MyController", ['$scope','$timeout',function($scope, $timeout){
$scope.callThis = function() {
console.log("I am called after 2 seconds from scope");
}
$timeout(function(){
$scope.callThis();
},2000);
}]);
All the above is also true for the $interval( ) service.
Now an important thing to note is if the function we schedule for execution makes changes to variables in the $scope object, or make changes to any other variable which our application is watching, the application needs to execute $scope.$digest( ) after the scheduled function call finishes. It is the default behavior of AngularJS to automatically call $scope.$digest( ) but it can get tricky if we are juggling through scopes inside an ngRepeat loop. For remedy we have an optional third boolean parameter in both the $timeout( ) and $interval( ) services which lets us explicitly specify whether to call the function scheduled inside a $apply( ) block or not. This sometimes helps us in avoiding the $inprog error which complains that we tried to execute a $apply in the middle of another $digest cycle.