My code includes a timeout loop structured 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 seems that the use of "this" within the onTimeout callback function is causing issues, whereas it functions correctly in startTimer and stopTimer. How can I resolve this?
UPDATE:
Because the context of "this" is lost inside onTimeout as explained in one of the answers below, I attempted to pass it in like this:
onTimeout: function (self) {
self.autoRefreshInSec--;
if (self.autoRefreshInSec <= 0) {
self.autoRefreshInSec = self.autoRefreshInterval;
self.doRefresh();
}
self.myTimeout = $timeout(self.onTimeout(self), 1000);
},
startTimer: function () {
this.autoRefreshInSec = this.autoRefreshInterval;
this.myTimeout = $timeout(this.onTimeout(this), 1000);
},
Interestingly, while debugging the code appeared to work. However, upon removing breakpoints, self.doRefresh() starts executing continuously. Why is this happening?
UPDATE 2:
To demonstrate the issue, I have created a JSFiddle at http://jsfiddle.net/qY86q/1.