Implementing Timers with $interval and $timeout Services

AngularJS’s $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 below:

Image callback: Is executed when the delay has expired.

Image delay: Specifies the number of milliseconds to wait before executing the callback function.

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

Image invokeApply: A Boolean that, if true, causes the function to only execute 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
3.131.38.14