gpt4 book ai didi

javascript - typescript 中的不活动检查

转载 作者:搜寻专家 更新时间:2023-10-30 21:07:09 25 4
gpt4 key购买 nike

我在对我的网站进行不活动检查时遇到问题。我在 StackOverflow 上找到了代码示例关于如何进行简单的不活动检查。这行得通

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

};

由于我在做 typescript ,所以我将代码重写到一个类中。不活动检查有效。它导航到另一个页面。我遇到的问题是,当有事件时,它也会导航到另一个页面。我调试了代码并调用了 cleartimeout 代码,但它仍然以某种方式执行。有人知道我做错了什么吗?这是我在 typescript (v1.7) 中创建的类<​​/p>

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

}

这就是我所说的:

module Home {
var inactivity: Inactivity;


export function init() {
//inactivityTime(); //javascript code that works
inactivity = new Inactivity();
inactivity.startChecking();
}
}

最佳答案

我认为问题很可能与上下文有关。尝试为 this 绑定(bind)正确的值:

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

}

关于javascript - typescript 中的不活动检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37858556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com