首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用止动节流阀将鼠标事件节流一段时间,从我们的应用程序中自动注销用户。

使用止动节流阀将鼠标事件节流一段时间,从我们的应用程序中自动注销用户。
EN

Stack Overflow用户
提问于 2015-07-27 02:33:40
回答 1查看 765关注 0票数 1

在我的项目中,我有一个需求,我需要在30分钟的不活动之后添加注销用户的能力。我的项目使用打字稿和棱角。

我可以在不活动30分钟后登录用户,但由于鼠标移动会导致web应用程序的过度使用,我想使用油门/退出。

下面的代码与节流阀有一个问题。

假设第一次单击用户事件发生在7:30,这将在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被注销。

我不确定我是否正确地使用了节流阀。如有任何指导,将不胜感激。

代码语言:javascript
复制
    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()));
   }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-27 13:02:53

我对你的问题采取了另一种更简单的方法。检查以下代码:

代码语言:javascript
复制
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。这使得取消该功能成为最好的解决方案:

  1. 当代码初始化时,安排执行;
  2. 如果在this.timer毫秒内没有发生单击,您将被注销;
  3. 如果单击,下一次执行将从现在起排定为this.timer毫秒。
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31644150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档