Javascript timeout when no actions from user for specified time

后端 未结 7 1027
广开言路
广开言路 2020-12-28 19:32

I want to call a js function when there is no activity from user on the web page for specified amount of time. If there is activity from user then reset timeout. I tried to

7条回答
  •  无人及你
    2020-12-28 20:18

    // Using jQuery (but could use pure JS with cross-browser event handlers):
    var idleSeconds = 30;
    
    $(function(){
      var idleTimer;
      function resetTimer(){
        clearTimeout(idleTimer);
        idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
      }
      $(document.body).bind('mousemove keydown click',resetTimer); //space separated events list that we want to monitor
      resetTimer(); // Start the timer when the page loads
    });
    
    function whenUserIdle(){
      //...
    }
    

    Edit: Not using jQuery for whatever reason? Here's some (untested) code that should be cross-browser clean (to a point; doesn't work on IE5 Mac, for example ;):

    attachEvent(window,'load',function(){
      var idleSeconds = 30;
      var idleTimer;
      function resetTimer(){
        clearTimeout(idleTimer);
        idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
      }
      attachEvent(document.body,'mousemove',resetTimer);
      attachEvent(document.body,'keydown',resetTimer);
      attachEvent(document.body,'click',resetTimer);
    
      resetTimer(); // Start the timer when the page loads
    });
    
    function whenUserIdle(){
      //...
    }
    
    function attachEvent(obj,evt,fnc,useCapture){
      if (obj.addEventListener){
        obj.addEventListener(evt,fnc,!!useCapture);
        return true;
      } else if (obj.attachEvent){
        return obj.attachEvent("on"+evt,fnc);
      }
    } 
    

提交回复
热议问题