Dmitriy Apollonin
Dmitriy Apollonin

Reputation: 1478

how to notify about $interval end in angularjs

I want to make custom animation in my web application, and i'm using $interval method to do some visual effects. And all i want is to know, when that animation ends.

For example

var myInterval = $interval(function(){
    //do some staff
}, 10, 20);

How can i get notify about that interval ends? Except $timeout(fn, 200), of course.

And the second question is also about notifying, but in case, when i cancel that interval is other place manually by $interval.cancel(myInterval), can i get notified about that?

Upvotes: 1

Views: 1184

Answers (2)

grantpatterson
grantpatterson

Reputation: 425

For the first case, you can just do:

myInterval.then(function () { console.log("Finished."); } );

It isn't a good idea to count the number of iterations when Angular is already doing that for you.

See https://docs.angularjs.org/api/ng/service/$q

Upvotes: 3

xsh.7
xsh.7

Reputation: 6250

You can broadcast an event by yourself when canceling the interval. Take a look at $rootScope.$broadcast().

Where you cancel the interval:

$rootScope.$broadcast('Custom::Event');

Where you want to retrieve the broadcast:

$scope.$on('Custom::Event', function (e) { ... });

Edit: Iterations

If you want to send the broadcast after the last iteration, check the first parameter provided to the function for the $interval.

$interval(function (iteration) {

  // Do some stuff...

  // Broadcast after last iteration
  if (iteration === iterations - 1) {
    $scope.$broadcast('Interval::Finished');
  }
}, delay, iterations);

See: JS Bin

Upvotes: 1

Related Questions