1

I want to make a function being called in a certain interval of time inside the constructor. But I don't want to write the function inside the $interval statement because it's a little big. So I wanted to make something like this:

this.$interval(this.getSomething(), 1000);

And the initialize it outside of the controller's constructor:

getSomething = function getSomething(){
                 ...
};

But it gives me an error of TypeError: fn is not a function When it seems to me as a function... Any suggestions?

  • 1
    According to [AngularJS $interval documentation](https://docs.angularjs.org/api/ng/service/$interval) it expects a callback. Changing your interval part to: this.$interval(this.getSomething, 1000); should work. (`()`removed) – dquijada Dec 18 '18 at 10:19
  • @dquijada — Depends on if `getSomething` makes use of `this` internally or not. – Quentin Dec 18 '18 at 10:20
  • Well, yes, @Quentin; but that's a more specific case. The only answer below can be checked for that case – dquijada Dec 18 '18 at 10:23
  • It actually makes use of `this` internally... What's the difference? Do I have to create a var pointing to this outside and send it via argument? Going to check if the previous comments work :) Thanks for the help – David Coelho Dec 18 '18 at 10:29
  • 1
    @DavidCoelho — See [this](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) and [this](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Quentin Dec 18 '18 at 10:31
  • Thanks @Quentin. Going to read it :) – David Coelho Dec 18 '18 at 10:37
  • 1
    And btw, @dquijada solution worked just fine. Thanks for the help :D – David Coelho Dec 18 '18 at 10:37

1 Answers1

-1

Try changing your function declaration to this.

getSomething = function(){
                 ...
};

and call your interval part like this.

this.$interval(function(){ this.getSomething() }, 1000);
holydragon
  • 6,158
  • 6
  • 39
  • 62
  • 1
    Using an anonymous function expression instead of a named function expression will not make any difference (unless the function tries to call itself recursively, in which case it will break it). – Quentin Dec 18 '18 at 10:19
  • `function(){ this.getSomething() }` won't work because the `this` context will have changed between functions. – Quentin Dec 18 '18 at 10:39