3

I'm having a problem with an inactivity check for my website. I've found a code sample on StackOverflow on how to do a simple inactivity check. And this works

var inactivityTime = function () {
    var t;
    window.onload = resetTimer;
    document.onmousemove = resetTimer;
    document.onkeypress = resetTimer;

    function logout() {
        location.href = 'logout.aspx'
    }

    function resetTimer() {
        clearTimeout(t);
  t = setTimeout(logout, 1000 * 60 * 1);
    }

};

Since I'm doing typescript, I rewrote the code into a class. The inactivity check works. it navigates to another page. The problem I have is that it also navigates to the other page when there is activity. I debugged the code and the cleartimeout code is called, but somehow it still executes. Does somebody know what I'm doing wrong? this is the class I made in typescript (v1.7)

class Inactivity {

 private timerHandle: number = null;

 constructor() {
 }

 startChecking() {
  this.resetTimer();
  window.onload = this.resetTimer;
  document.onmousemove = this.resetTimer;
  document.onkeypress = this.resetTimer;
 }

 stopChecking() {
  if (this.timerHandle) {
   clearTimeout(this.timerHandle);
   this.timerHandle = null;
  }
 }

 private resetTimer() {
  if (this.timerHandle) {
   clearTimeout(this.timerHandle);
   this.timerHandle = null;
  }
  this.timerHandle = setTimeout(this.logout, 1000 * 60 * 1);
 }

 private logout() {
  location.href = 'logout.aspx';
 }

}

and this is where I call it:

module Home {
    var inactivity: Inactivity;


    export function init() {
      //inactivityTime(); //javascript code that works
      inactivity = new Inactivity();
      inactivity.startChecking();
    }
}
Community
  • 1
  • 1
Sebastian S
  • 285
  • 2
  • 16

1 Answers1

5

I think the problem is most likely about context. Try binding the correct value for this:

class Inactivity {

    private timerHandle: number = null;

    constructor() {
    }

    startChecking() {
        this.resetTimer();

        // Bind the methods to the proper context
        window.onload = this.resetTimer.bind(this);
        document.onmousemove = this.resetTimer.bind(this);
        document.onkeypress = this.resetTimer.bind(this);
    }

    stopChecking() {
        if (this.timerHandle) {
            clearTimeout(this.timerHandle);
            this.timerHandle = null;
        }
    }

    private resetTimer() {
        if (this.timerHandle) {
            clearTimeout(this.timerHandle);
            this.timerHandle = null;
        }
        this.timerHandle = setTimeout(this.logout, 1000 * 60 * 1);
    }

    private logout() {
        location.href = 'logout.aspx';
    }

}
Schlaus
  • 18,144
  • 10
  • 36
  • 64