简体   繁体   中英

How can I call a function after an interval has finished?

I have an $interval that calls a certain number of times.

When the interval has finished running, I want it to call a final reset function. How can I do this?

ie.

  $scope.clickme = function() {
    var i = 0;

    function lerp() {
      alert(i++);
    }

    function fin(){    //how do I call this function? 
        alert ("all done!")
    }

    $interval(lerp, 500, 5);
  };

JSFiddle: http://jsfiddle.net/h4cn32e6/1/

The return value of registering an interval function is a promise. This promise will be notified upon each tick of the interval, and will be resolved after count iterations

So:

$interval(lerp, 500, 5).then(fin);

$interval returns a promise, which will be resolved when it has finished executing all of its iterations.

Just use promise.then to execute the final task..

  $scope.clickme = function() {
    var i = 0;

    function lerp() {
      alert(i++);
    }

    function fin(){
        alert ("all done!")
    }

    var promise = $interval(lerp, 500, 5);

    promise.then(fin);
  };

http://jsfiddle.net/0wuwnhxo/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM