3

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...

0

3 Answers 3

6

If setInterval calls the function it doesn't set the this value as you may expect. Calling this.tick() does set it correctly, but just passing the function and having it called in another way does not. You have to bind the this value to what you want:

setInterval(this.tick.bind(this), 1000);

This is available on newer browsers but there are shims available.

Also, you probably meant this.sessionExpired(), as that's where it's defined. return doesn't make much sense there since setInterval does not care about the return value.

Sign up to request clarification or add additional context in comments.

3 Comments

You could also use the "that" trick: var that = this; return setInterval(function(){ return that.tick()}, 1000)
I ended up using the 'that' solution, as I need support for older browsers (curse you asp!) but I appreciate the help!
@missingno: True. Here it's just a matter of fixing the this value so I think .bind is a neat solution.
0

Have you ever set the timeout? You might want

sessionmanager.timeout=0;

somwhere in the class definition.

3 Comments

I have this.timeout = 0 in the constructor?
An instance has a .timeout value, not the constructor itself.
@Flying Streudel: No, your code is correct there :) The suggestion to set sessionmanager.timeout does not make much sense.
0

In ES7 Javascript you can do the following:

window.setInterval(::this.tick, 1000);

The double colon syntax :: is a shortcut to .bind(this).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.