I have a timeout loop like this:
var somedata = {
autoRefreshInterval: 300,
autoRefreshInSec: 300,
myTimeout: null,
doRefresh: _doRefresh,
onTimeout: function () {
this.autoRefreshInSec--;
if (this.autoRefreshInSec <= 0) {
this.autoRefreshInSec = this.autoRefreshInterval;
this.doRefresh();
}
this.myTimeout = $timeout(this.onTimeout, 1000);
},
startTimer: function () {
this.autoRefreshInSec = this.autoRefreshInterval;
this.myTimeout = $timeout(this.onTimeout, 1000);
},
stopTimer: function () {
$timeout.cancel(this.myTimeout);
},
}
It appears that the "this" doesn't work inside of onTimeout callback function, while it works fine for startTimer and stopTimer. How to fix it?
UPDATE:
Since this is lost inside the onTimeout based on one of the answers below, I tried to pass it into like this:
onTimeout: function (self) {
self.autoRefreshInSec--;
if (self.autoRefreshInSec <= 0) {
self.autoRefreshInSec = self.autoRefreshInterval; // Set it here so that it does't start refresh right away. It will be reset when refresh is done.
self.doRefresh();
}
self.myTimeout = $timeout(self.onTimeout(self), 1000);
},
startTimer: function () {
this.autoRefreshInSec = this.autoRefreshInterval;
this.myTimeout = $timeout(this.onTimeout(this), 1000);
},
Strangely, when I debug through the code, it seems working. However, once I removed the break points, self.doRefresh() is fired continuously. Why?
UPDATE 2:
Okay, I created a JSFiddle at http://jsfiddle.net/qY86q/1 to illustrate the problem.
AngularJS?$timeoutservice. Where do you inject it in your code?thisrefers to the function you are in. So inside your$timeout.cancel()it refers to the function$timeout. Just use the name itself.