Search code examples
javascriptsettimeoutcleartimeout

How to clear setTimeout inside Javascript Object?


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?


Solution

  • 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);
    }