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);
};

Javascript Functions Holding Their Own Data

In Javascript functions are objects, a fact most of us overlook. They are special callable objects but still just objects. Because of this, functions have properties. For example MyFunction.name will return the name of the function. Recently I was reading the excellent JavaScript Patterns book which reiterated this fact about functions but this time I suddenly had a light bulb moment. I started thinking about use cases where this could be useful and the concept became fascinating. Just imagine it, functions that hold their own state! Functions that cache their calculations within themselves! No more external variables to hold data that is tightly coupled to the function. What a cool idea! This, of course, is not a new idea it’s the concept of Memoization.

Example 1

You have an initialization function that you want to ensure only runs once.

function Init()
{
    if(Init.initialized)
        return;

    // Do stuff

    Init.initialized = true;
}

Example 2

Let’s say you have a function that builds and returns an HTML element. After building the element you could cache a reference to it locally in the function. This keeps the function self contained and efficient since it’s not using any external variables and it only builds the element once.

function GetWidgetElement()
{
    if(GetWidgetElement.element)
      return GetWidgetElement.element;

    var div = document.createElement("div");
    div.className = "myWidget";

    return GetWidgetElement.element = div;
}

Downsides

Of course just because we can store data in functions doesn’t mean we necessarily should. I’m sure a good argument could be made that it’s bad programming practice. That it makes the code less understandable. Most people might get quite confused if they don’t know functions are objects with properties. This technique could most definitely be abused. The properties are still public to anyone that has access to the function so you aren’t shoving it into a secret hiding space.

When introduced carefully I think this trick could be used to fantastic effect. Creating functions that rely less on external variables to hold state/data when it’s only relevant to that function sounds like a good idea to me.

The Price of Mastery

After finally watching the supremely fascinating documentary Jiro Dreams of Sushi I have become absorbed with the questions surrounding the mastering one’s skills. The documentary details the life of one of the most legendary sushi chefs of all time who is still going strong 90 years on. Jiro’s dedication to his craft is shocking. He has devoted every fiber of his being to the pursuit of mastering a single skill. He is not in it for the money or the prestige; he wakes up every morning mesmerized with the idea of improving over the previous day. It is hinted that the cost has been high. His role as a father and husband suffered greatly and he has forgone a great many nights and weekends. However, his sacrifices have molded him into a legend. A person of incredible stature both among his peers and worldwide audience.

Which brings me to my central question. Is the pursuit of mastery worth it? For any skill each of us, whether conscious or not, choose the level of proficiency we are content with. Is it worth giving up nights, weekends, money, time with family or friends? There is no right answer, of course, it is an individual choice. It is also a choice we may regret either way. Will we regret taking time away from our children or perhaps wish we had skipped the weekend parties to focus?

For myself it is a vexing question. What level of skill am I satisfied with? How far am I willing to go for success? What is my definition of success? In the fast paced world of software development the constant push to acquire new skills and hone existing is less of a choice then a requirement. I believe that facing this question head-on and weighing the pros and cons on the scale of life is the best way to be at peace with either choice.

Perhaps most surprising is that even 90 year old Jiro, a legend that has spent decades learning, working, and experimenting, believes that he has not yet reached the apex. That he can still do better. That there is still more to learn. Is mastery itself a mirage on the horizon that can never be reached? Why bother, after all, won’t there always be someone younger, better, faster, stronger, smarter? I believe the only sane way to come to terms with this is to let all other competition melt away leaving only yourself. Specifically yourself from yesterday. Am I better, faster, stronger, or smarter than I was yesterday?

Leaving me with the same question, what level of mastery am I content with? I suspect this will require more thought… :)