使用 lodash throttle 来限制鼠标事件一段时间,并自动从我们的应用程序中注销用户

Using lodash throttle to throttle mouse events for some time wiring with automatic logout of user from our application

我在我的项目中有一个要求,我需要添加在 30 分钟不活动后注销用户的功能。我的项目使用 typescript 和 angular.

我可以在 30 分钟不活动后注销用户,但由于鼠标移动会导致我想使用的 Web 应用程序过度杀伤 throttle/debounce。

以下带油门的代码有问题。

假设第一次点击用户事件发生在 7。这会在 7:30 启动注销计时器。

现在因为我已经使用了29分钟的油门,除了最后一次点击之外,从(7-7:29)开始的任何点击都会被忽略。假设最后一次点击发生在 7:16。现在下一个油门计时器从 7:30 开始,并且由于上次事件点击是 7:16,代码智能地将计时器设置为 7:46。现在假设 throttle no 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()));
   }

我对你的问题采取了不同的、更简单的方法。检查以下代码:

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.logoutInactiveUserthis.timer 毫秒后执行,前提是在此超时期间没有发生任何其他事情。这使得消除该功能成为最佳解决方案:

  1. 您在代码初始化时安排执行;
  2. 如果在 this.timer 毫秒内没有点击,您将被注销;
  3. 如果您点击,下一次执行将安排在 this.timer 毫秒后。