function UITimer(interval, callbakFunction) {
this.t = null;
this.isRunning = 0;
this.interval = interval;
this.callbackFunction = callbakFunction;
};
UITimer.prototype.timeCount = function () {
alert(this.interval);
this.callbackFunction();
this.t = setTimeout(this.timeCount, this.interval);
}
UITimer.prototype.startTimer = function () {
if (!this.isRunning) {
this.isRunning = 1;
this.timeCount();
}
}
UITimer.prototype.stopTimer = function () {
clearTimeout(this.t);
this.isRunning = 0;
}
var uiTimer = new UITimer(5000, PhotoService.GetRandomImage);
uiTimer.startTimer();
The first time this.interval = 5000, second time it is undefined. I replaced the interval by a constant value but this line this.t = setTimeout(this.timeCount, 5000); could not run the second time. What is the problem?
The
thisvalue gets lost when passing a function.foo.bar()setsthistofooinsidebar, but when storing/passing the value and calling it later, this does not happen.Use
.bindto force thethisvalue insidetimeCount:Or, pass another function that calls
timeCount. Beware though, sincethischanges inside functions, you’d have to save a reference to the correctthisvalue: