Confusion about how the promise returned by $interval works compared to $timeout in Angular

后端 未结 2 823
无人及你
无人及你 2021-01-21 00:52

I\'m having an issue understanding how the promise returned by $interval works in Angular.

Let\'s say in the following example, we have a simple \"api\" factory with a

2条回答
  •  借酒劲吻你
    2021-01-21 01:36

    The only thing you can do with the promise returned by $interval is cancel it (to stop its execution):

    var handle = $interval(someFunc, 1000);
    ...
    $interval.cancel(handle);
    

    Your code should probably look like:

    app.controller('appCtrl', function($scope, $interval, api) {
        $interval(function() {
            console.log(api.getStuff());
        }, 1000);
    });
    

    To be fancy and see everything working together:

    app.controller('appCtrl', function($scope, $interval, $timeout, api) {
        var handle = $interval(function() {
            console.log(api.getStuff());
        }, 1000);
    
        $timeout(function() {
            $interval.cancel(handle);
        }, 5000);
    });
    

提交回复
热议问题