* @ngdoc service * @name $interval * * @description * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay` * milliseconds. * * The return value of registering an interval function is a promise. This promise will be *
(fn, delay, count, invokeApply)
| 11596 | * </example> |
| 11597 | */ |
| 11598 | function interval(fn, delay, count, invokeApply) { |
| 11599 | var hasParams = arguments.length > 4, |
| 11600 | args = hasParams ? sliceArgs(arguments, 4) : [], |
| 11601 | setInterval = $window.setInterval, |
| 11602 | clearInterval = $window.clearInterval, |
| 11603 | iteration = 0, |
| 11604 | skipApply = (isDefined(invokeApply) && !invokeApply), |
| 11605 | deferred = (skipApply ? $$q : $q).defer(), |
| 11606 | promise = deferred.promise; |
| 11607 | |
| 11608 | count = isDefined(count) ? count : 0; |
| 11609 | |
| 11610 | promise.then(null, null, (!hasParams) ? fn : function() { |
| 11611 | fn.apply(null, args); |
| 11612 | }); |
| 11613 | |
| 11614 | promise.$$intervalId = setInterval(function tick() { |
| 11615 | deferred.notify(iteration++); |
| 11616 | |
| 11617 | if (count > 0 && iteration >= count) { |
| 11618 | deferred.resolve(iteration); |
| 11619 | clearInterval(promise.$$intervalId); |
| 11620 | delete intervals[promise.$$intervalId]; |
| 11621 | } |
| 11622 | |
| 11623 | if (!skipApply) $rootScope.$apply(); |
| 11624 | |
| 11625 | }, delay); |
| 11626 | |
| 11627 | intervals[promise.$$intervalId] = deferred; |
| 11628 | |
| 11629 | return promise; |
| 11630 | } |
| 11631 | |
| 11632 | |
| 11633 | /** |