Abstract Composition Because everyone has to have a blog, right?

Detecting User Inactivity In Javascript

You may face a time when you have javascript that is polling the server and you need to detect when the user stops interacting with the page. If you don’t shut off the poling at some point it will keep the user active/logged-in forever, which is certainly not a good thing. Now, I’m pretty sure that these days polling would technically be considered bad practice and a situation you should never find yourself in. Yeah well, whatever, &*$# happens and in the real world you might face this in legacy code or something.

Also there might be other situations where you need to detect this state. Here is some code I wrote that continues some activity until the user is inactive for some period of time and then stop.

Activity is defined as the user moving the mouse or typing anywhere inside the page. I believe this will also capture other pointing devices or taps as well but have not tested it.

Unfortunately the code does have to attach event handlers to the document level mousemove and keypress events, which adds excess weight to the page. However the code run in these events is pretty minimal so it shouldn’t cause too much of a performance drain. However, it should be used sparingly!

var DoWhileUserIsActive = function(func, msInterval, maxIdleMins)
{
  /// <summary>
  ///   Executes the function every interval until user is idle
  ///   for the max amount of time.
  /// </summary>
  /// <param name="func" type="Function">
  ///   The function to run every interval.
  /// </param>
  /// <param name="msInterval" type="Number">
  ///   Specified function will run every number of
  ///   milliseconds specified.
  /// </param>
  /// <param name="maxIdleMins" type="Number">
  ///   Minutes user should be idle before stopping the
  ///   function (default 10 mins).
  /// </param>

  maxIdleMins = maxIdleMins || 10;
  var userIsIdle = false;

  // Kick off specified function to run every interval
  var intervalID = setInterval(func, msInterval);
  var enabled = true;

  // Every minute update the idle count. If we hit max mins idle
  // then stop the specified function from running
  var minsIdle = 0;
  setInterval(function()
  {
    minsIdle++;
    if(minsIdle >= maxIdleMins)
    {
      clearInterval(intervalID);
      userIsIdle = true;
    }
  }, 60000);

  // When user interacts with page reset idle count and
  // start up activity again
  var handleActivity = function()
  {
    if(minsIdle >= maxIdleMins && userIsIdle)
      intervalID = setInterval(func, msInterval);

    minsIdle = 0;
  };
  document.addEventListener("mousemove", handleActivity);
  document.addEventListener("keypress", handleActivity);
};