Confusion about how a promise returned by $ interval compares to $ timeout in Angular

I am having a problem understanding how a promise returned by a $ interval works in Angular.

Let's say in the following example, we have a simple "api" factory with a method called "getStuff" that returns an array with one element. We also have a controller that calls $ timeout on this factory:

angular.module("app",[])
  .factory('api', function(){
    return {
      getStuff: function() {      
        return ["stuff"];
      } 
    };   
  })
  .controller('appCtrl', function($scope, $timeout, api){
    $timeout(api.getStuff, 1000)
      .then(function(response){
        console.log(response);
      });
  })

      

This will write '["stuff"]' to the console after 1 second, which is great.

So let's say I want to call this method every time, replacing $ timeout with $ interval. Now nothing happens:

angular.module("app",[])
  .factory('api', function(){
    return {
      getStuff: function() {      
        return ["stuff"];
      } 
    };   
  })
  .controller('appCtrl', function($scope, $interval, api){
    $interval(api.getStuff, 1000)
      .then(function(response){
        console.log(response);
      });
  })

      

In this case, the difference between $ timeout and $ interval?

I appreciate all the help!

+3


source to share


2 answers


The only thing you can do with a promise being returned $interval

is to cancel it (to stop it from being executed):

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

      

Your code should probably look like this:



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

      

Be fantasy and see everything that works together:

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

    $timeout(function() {
        $interval.cancel(handle);
    }, 5000);
});

      

+4


source


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

/* APP MODULE */
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>
      

Run codeHide result




Output:

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

      

The final result is the final result.

+8


source







All Articles