Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inactivity check in typescript

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();
    }
}
like image 240
Sebastian S Avatar asked Dec 01 '25 09:12

Sebastian S


1 Answers

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';
    }

}
like image 130
Schlaus Avatar answered Dec 04 '25 03:12

Schlaus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!