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

 ̄綄美尐妖づ 提交于 2019-12-01 21:34:02

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);
});

Added the count value to the example that the DIMM Reaper's provided in a comment to Christophe L's answer:

var app = angular.module("app", []);

app.run(function ($interval) {
    console.log('This fiddle will self destruct...');
    
    var timer = $interval(function (count) {
        console.log('tick... ' + count);
    }, 500, 4, false);
    
    timer.then(function(res) {
        console.log("BOOM! " + res);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>

<body ng-app="app">
</body>

Output:

This fiddle will self destruct...
tick... 1
tick... 2
tick... 3
tick... 4
BOOM! 4

The final result is the final count.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!