0

I have an object that I have a few functions inside that I am using setTimout inside. I'm trying to clear the timeout using clearTimeout.. but I'm not hitting it right.

var ExpireSession = {
    killSession: function () {
        var TESTVAR2 = setTimeout(function () {
            window.location.href = "error/expired.aspx";
        }, 15000);
    },

    stopTimers: function (){
        clearTimeout(ExpireSession.killSession.TESTVAR2)
    }
}

Before 15 seconds I am triggering: ExpireSession.stopTimers(); but it does not stop it. Any ideaas what I am doing wrong here?

1
  • 1
    You've to define the timer as a property of ExpireSession. Commented Mar 30, 2015 at 14:28

2 Answers 2

2

var TESTVAR2 is a variable that is local to the function it is declared within. It is not a property of an object.

If you want to access it as a property of an object, then you must define it as such:

ExpireSession.killSession.TESTVAR2 = setTimeout(function () {

(You might be able to make use of this depending on how you call the function).

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

Comments

1

Because JavaScript has functional scope, TESTVAR2 will only be defined within killSession. To reference it, you can set it as a property of ExpireSession:

killSession: function () {
  this._TESTVAR2 = setTimeout(function () {
    window.location.href = "error/expired.aspx";
  }, 15000);
},
stopTimers: function () {
  clearTimout(this._TESTVAR2);
}

2 Comments

This worked, thank you. Can you explain why adding "this" to the variable made it accessible? I'm not following. Thank you!
When using a var declaration, you are defining a local variable. In JavaScript, these are local to the scope (in this case a function) where they were defined. When you are using this here, you are actually adding a property to ExpireSession. That is, ExpireSession._TESTVAR2 is your timeout. Because killSession and stopTimers are properties of ExpireSession, they can both access the _TESTVAR2 property.

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.