I have a class I am attempting to use to manage a session on the client side, it looks like this:
var sessionmanager;
sessionmanager = (function() {
sessionmanager.name = 'sessionmanager';
function sessionmanager(timeout, action) {
if (action != null) {
this.action = action;
} else {
this.action = null;
}
if (timeout != null) {
this.timeout = timeout * 60;
} else {
this.timeout = 0;
}
}
sessionmanager.prototype.run = function() {
return window.setInterval(this.tick, 1000);
};
sessionmanager.prototype.sessionExpired = function() {
if (this.action != null) {
window.navigate("timeout.asp");
}
};
sessionmanager.prototype.setTimeout = function(timeout) {
return this.timeout = timeout;
};
sessionmanager.prototype.tick = function() {
this.timeout -= 1;
if (this.timeout < 1) {
return sessionExpired();
}
};
return sessionmanager;
})();
However when I debug inside the tick function that is called from within the setInterval callback I get this.timeout = NaN
I am guessing I scoped something incorrectly? Help please? I am new to javascript…
If
setIntervalcalls the function it doesn’t set thethisvalue as you may expect. Callingthis.tick()does set it correctly, but just passing the function and having it called in another way does not. You have to bind thethisvalue to what you want:This is available on newer browsers but there are shims available.
Also, you probably meant
this.sessionExpired(), as that’s where it’s defined.returndoesn’t make much sense there sincesetIntervaldoes not care about the return value.