我的项目中有一个要求,我需要添加在30分钟不活动后注销用户的功能。我的项目使用typescript和angular。
我可以在30分钟不活动后将用户注销,但由于鼠标移动会导致网络应用程序过度使用我想使用油门/去抖动。
下面有节流的代码有问题。
假设首次单击用户事件发生在7.这将启动一个计时器,以便在7:30注销。
既然我已经使用了29分钟的节流,那么除了最后一次点击之外的任何点击(7-7:29)都会被忽略。假设最后一次点击发生在7:16。现在下一个节流计时器从7:30开始,并且自上次事件点击是7:16以来,代码智能地将计时器设置为7:46。现在假设在2号油门中,事件发生在7:42,现在由于此油门将持续到7:58,计时器不能重置到7:59,因此即使事件发生在7:42,用户也会得到在7:46退出。
我不确定我是否正确使用了油门。任何指导都将非常感谢。
constructor(public $element,public userService){
this.timer=60000; //Just for checking purpose it is 1 minute
this.setInactivityTimer();
this.timeNewTimer=this.timer;
this.myThrottleFunc = _.throttle(function(event){
this.timeofLastEventInThrottle=event.timeStamp;
this.timeNow=new Date().getTime();
console.log("Event Triggered at"+ " "+(new
Date(this.timeofLastEventInThrottle)));
this.timeNewTimer =this.timer-(this.timeNow-
this.timeofLastEventInThrottle);
clearTimeout(this.timeoutTimer);
if(!this.hasFirstEventOccured)
this.setFirstEventInThrottleTimer();
else {
this.setSubsequentEventsInThrottleTimer();
//this.myThrottleFunc.cancel();
}
}.bind(this),this.timeNewTimer-1000);
$element.on('click',this.myThrottleFunc);
}
public setInactivityTimer() {
this.timeoutTimer=setTimeout(() => {
this.logoutInactiveUser();
},this.timer)
}
private setFirstEventInThrottleTimer() {
console.log("Timer" + " "+ this.timer);
this.timeoutTimer=setTimeout(() => {
this.logoutInactiveUser();
}, this.timer);
this.hasFirstEventOccured=true;
}
private setSubsequentEventsInThrottleTimer () {
console.log("New Timer" + " "+ this.timeNewTimer);
this.timeNow=new Date().getTime();
clearTimeout(this.timeoutTimer);
this.timeoutTimer=setTimeout(() => {
this.logoutInactiveUser();
}, this.timeNewTimer);
}
public logoutInactiveUser(){
console.log("Logout at" + " "+ (new Date()));
}
答案 0 :(得分:2)
我对你的问题采取了一种不同的,更简单的方法。请检查以下代码:
constructor (public $element) {
this.timer = 60000;
this.debouncedLogout = _.debounce( this.logoutInactiveUser, this.timer );
this.debouncedLogout();
$element.on("click", this.debouncedLogout );
}
public logoutInactiveUser(){
console.log("Logout at" + " "+ (new Date()));
}
如果在此超时期间没有其他任何事情发生,您需要在this.logoutInactiveUser
毫秒后执行this.timer
。这使得该函数的去抖动成为最佳解决方案:
this.timer
毫秒期间没有发生任何点击,您将被注销; this.timer
毫秒。