setTimeout and setInterval


#1

so i have a piece of code

this.twm = 5; this.rate = 5; // but it changes dynamically with another function (not included)

rateOfMass() {

if (this.rate >= 5)
this.twm ++;
console.log(this.twm);

}

setInterval(this.rateOfMass, 1000);

the problem is

because of the setInterval function the code inside my rateOfMass function does not have access to the variables that where defined outside of it (in this case : this.twm and this.rate)
This was also the case when i tried to make the function using SetTimeout instead

the console log comes up with: undefined

does anyone know if this is just a angular2 bug and/or if there is a solution to this?

thanks in advance


#2

I can’t see the full context of how you are defining your rateOfMass etc however I can see that you are calling setInterval incorrectly.

setInterval expects a function reference or code block… you have given it the results of your rateOfMass function call.

It should be something along the lines of

setInterval(this.rateOfMass, 1000);

you could of course use a closure.


#3

Sorry about that, just edited my post to correct that mistake :confused: it was done correctly in my actual code , I incorrectly typed it back out when writing this post

But my problem still exists unfortunately.


#4

:smile: that makes more sense.

Unfortunately I still can’t see enough of your controller to see the context of where you are setting stuff up.


#5

it should be setInterval(() => {this.rateOfMass()},1000); right?