Implementing Timers with $interval and $timeout Services

The AngularJS $interval and $timeout services enable you to delay execution of code for an amount of time. These services interact with the JavaScript setInterval and setTimeout functionality—but within the AngularJS framework.

The $interval and $timeout services use the following syntax:

$interval(callback, delay, [count], [invokeApply]);
$timeout(callback, delay, [invokeApply]);

The parameters are described here:

callback: Is executed when the delay has expired.

delay: Specifies the number of milliseconds to wait before the callback function is executed.

count: Indicates the number of times to repeat the interval.

invokeApply: Is a Boolean that, if true, causes the function to execute only in the $apply() block of the AngularJS event cycle. The default is true.

When you call the $interval() and $timeout() methods, they return a promise object that you can use to cancel the timeout or interval. To cancel an existing $timeout or $interval, call the cancel() method. For example:

var myInterval = $interval(function(){$scope.seconds++;}, 1000, 10, true);
. . .
$interval.cancel(myInterval);

If you create timeouts or intervals by using $timeout or $interval, you must explicitly destroy them by using cancel() when the scope or elements directives are destroyed. The easiest way to do this is by adding a listener to the $destroy event. For example:

$scope.$on('$destroy', function(){
  $scope.cancel(myInterval);
});

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset