How do i detect if the user is “idle” with javascript?

后端 未结 4 1405
忘掉有多难
忘掉有多难 2020-12-17 23:05

I\'m developing a \"real-time\" web application which sends AJAX requests to the server every 10 seconds. Obviously this is very bandwidth-intensive and I would like to know

4条回答
  •  别那么骄傲
    2020-12-17 23:36

    You may want to listen for some or all of the following events:

    mouseMove, mouseClick, mouseUp, mouseDown, keyDown, keyUp, keyPress

    set a timer to go off after some duration of idleness (60 seconds?) and that will turn off your switch make sure you check your switch before your ajax requests.

    Ideally you'll exponentially throttle your ajax calls to some low value the longer a user remains idle.

    $(window).bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', someEvent);
    var active = true,
      delay = 60000,
      timer = null;
    
    function someEvent(e)
    {
      active = true;
      if (timer) clearTimeout(timer);
      timer = setTimeout(function(t){
        active = false;
      }, delay);
    }
    

提交回复
热议问题