600

Is it possible to detect "idle" time in JavaScript?

My primary use case probably would be to pre-fetch or preload content.

I define idle time as a period of user inactivity or without any CPU usage

2

38 Answers 38

503

With vanilla JavaScript:

var inactivityTime = function () {
    var time;
    window.onload = resetTimer;
    // DOM Events
    document.onmousemove = resetTimer;
    document.onkeydown = resetTimer;

    function logout() {
        alert("You are now logged out.")
        //location.href = 'logout.html'
    }

    function resetTimer() {
        clearTimeout(time);
        time = setTimeout(logout, 3000)
        // 1000 milliseconds = 1 second
    }
};

And initialise the function where you need it (for example: onPageLoad).

window.onload = function() {
  inactivityTime();
}

You can add more DOM events if you need to. Most used are:

document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer; // touchscreen presses
document.ontouchstart = resetTimer;
document.onclick = resetTimer;     // touchpad clicks
document.onkeydown = resetTimer;   // onkeypress is deprectaed
document.addEventListener('scroll', resetTimer, true); // improved; see comments

Or register desired events using an array

window.addEventListener('load', resetTimer, true);
var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
events.forEach(function(name) {
 document.addEventListener(name, resetTimer, true);
});

DOM Events list: http://www.w3schools.com/jsref/dom_obj_event.asp

Remember to use window, or document according your needs. Here you can see the differences between them: What is the difference between window, screen, and document in JavaScript?

Code Updated with @frank-conijn and @daxchen improve: window.onscroll will not fire if scrolling is inside a scrollable element, because scroll events don't bubble. In window.addEventListener('scroll', resetTimer, true), the third argument tells the listener to catch the event during the capture phase instead of the bubble phase.

19
  • 4
    definitely resetting a timer is a more direct/intuitive and accurate approach than having a timeout do its thing, only to keep an integer count of another thing, when the timer itself can BE the (high-precision) counter. Commented May 4, 2016 at 16:05
  • 2
    @mpsbhat just add an console.log or an alert an see if works. Or register this events: document.onload = function () { inactivityTime(); }; document.onmousedown = function () { inactivityTime(); }; document.onkeypress = function () { inactivityTime(); }; document.ontouchstart = function () { inactivityTime(); };
    – equiman
    Commented Jun 22, 2016 at 15:03
  • 2
    Yeah... Working. jsfiddle.net/mpsbhat/6b6mja5t/1. Thanks @equiman
    – mpsbhat
    Commented Jun 23, 2016 at 4:09
  • 7
    Would be much better to have a flag var notidle; set that flag = true only on the events. Then in the resetTimer function test if the notidle flag is true, if it is reset the timer their, or call logout. This will remove the complexity overhead of constantly resetting the timer.
    – MartinWebb
    Commented Nov 26, 2016 at 13:50
  • 2
    Simple / elegant solution I just updated and added the timeout as argument like: var inactivityTime = function (timeout) { so we have control of it form outside Commented Jan 31, 2018 at 13:16
500

Here is a simple script using jQuery that handles mousemove and keypress events. If the time expires, the page reloads.

<script type="text/javascript">
    var idleTime = 0;
    $(document).ready(function () {
        // Increment the idle time counter every minute.
        var idleInterval = setInterval(timerIncrement, 60000); // 1 minute

        // Zero the idle timer on mouse movement.
        $(this).mousemove(function (e) {
            idleTime = 0;
        });
        $(this).keypress(function (e) {
            idleTime = 0;
        });
    });

    function timerIncrement() {
        idleTime = idleTime + 1;
        if (idleTime > 19) { // 20 minutes
            window.location.reload();
        }
    }
</script>
16
  • 16
    You're missing a semicolon after the $(document).ready(function() body. Also, in the call to setInterval, it won't work with quotes around the function name and you don't need the parentheses after it. Just: setInterval(timerIncrement, 60000) Commented Apr 5, 2013 at 17:30
  • 11
    @Jesse: Your suggestions are all good, this is how the code should be. But I just wanted to point out that even without these changes, the code is fully functional. Semicolons at the end of an expression statement are optional and you can in fact pass a string to setInterval, which then gets evaluated as JavaScript. Commented Nov 17, 2013 at 17:51
  • 11
    You could simply use idleTime++; instead of idleTime = idleTime + 1; Commented Jan 16, 2014 at 4:30
  • 8
    Is this not heavy on a user's system? Let's say, a user with a fairly old browser on a not that heavy pc, is working in a javascript application for half a day, and it is processing these functions every time the user moves his mouse... I wonder if this won't affect the user's experience...
    – Sander
    Commented Jan 21, 2014 at 13:53
  • 6
    @PietBinnenbocht Also, if you start optimizing things like this, you may as well change every function that takes strings like 'mousemove keydown click' to use bit flags (Event.MOUSEMOVE | Event.KEYDOWN | Event.CLICK), since they are waaaaay faster than string operations. But do you really want to do this?
    – klh
    Commented May 9, 2014 at 3:32
129

Improving on Equiman's (original) answer:

function noIdlingHere() {

    function yourFunction() {
        // your function for too long inactivity goes here
        // e.g. window.location.href = 'logout.php';
    }

    let t; // must be declared here
    function resetTimer() {
        clearTimeout(t); // global function
        t = setTimeout(yourFunction, 600000);  // time is in milliseconds (10 min)
    } 

    window.addEventListener('load', resetTimer, true);
    window.addEventListener('mousemove', resetTimer, true);
    window.addEventListener('mousedown', resetTimer, true);
    window.addEventListener('touchstart', resetTimer, true);
    window.addEventListener('touchmove', resetTimer, true);
    window.addEventListener('click', resetTimer, true);
    window.addEventListener('keydown', resetTimer, true);
    window.addEventListener('scroll', resetTimer, true);
    window.addEventListener('wheel', resetTimer, true);
}

noIdlingHere();

Apart from the improvements regarding activity detection, and the change from document to window, this script actually calls the function, rather than letting it sit idle by.

It doesn't catch zero CPU usage directly, but that is impossible, because executing a function causes CPU usage. And user inactivity eventually leads to zero CPU usage, so indirectly it does catch zero CPU usage.

22
  • 10
    Just wanted to point out that window.onscroll will not fire if scrolling is inside a scrollable element, because scroll events don't bubble. Using window.addEventListener('scroll', resetTimer, true), the third argument tells the listener to catch event during capture phase instead of bubble phase (IE > 8), see this answer
    – DaxChen
    Commented Nov 23, 2017 at 2:45
  • @DaxChen -- Doesn't document.onscroll have the same problem, not firing if the scrolling is inside a scrollable child? Commented May 1, 2018 at 22:48
  • 2
    Yes, the point I was saying is to useaddEventListener instead of onscroll.
    – DaxChen
    Commented May 2, 2018 at 1:15
  • 1
    I'll update my answer with this important information, to avid other copy and paste my mistake. Thanks @DaxChen and Frank
    – equiman
    Commented Oct 18, 2019 at 11:56
  • 2
    btw onkeypress is depricated use onkeydown
    – BluePie
    Commented Sep 3, 2020 at 8:38
34

I have created a small library that does this:

https://github.com/shawnmclean/Idle.js

Description:

Tiny JavaScript library to report activity of user in the browser (away, idle, not looking at webpage, in a different tab, etc). that is independent of any other JavaScript libraries such as jQuery.

Visual Studio users can get it from NuGet by:

Install-Package Idle.js
0
33

Here is a rough jQuery implementation of tvanfosson's idea:

$(document).ready(function(){

   idleTime = 0;

   //Increment the idle time counter every second.
   var idleInterval = setInterval(timerIncrement, 1000);
   
   function timerIncrement()
   {
     idleTime++;
     if (idleTime > 2)
     {
       doPreload();
     }
   }
   
   //Zero the idle timer on any action.
   $(this).bind('mousemove keydown scroll click', function (e) {
       idleTime = 0;
       //Do something
   });
   
   function doPreload()
   {
     //Preload images, etc.
   }
   
})
4
  • 9
    This solution doesn't consider keyboard events. Commented Mar 1, 2010 at 12:43
  • 7
    Never pass setInterval a string! Just give a function as a variable!
    – Eric
    Commented Oct 7, 2011 at 14:08
  • 1
    This won't actually work because passing a string to setInterval() evaluates the expression in the global scope and thus it won't find the timerIncrement() function that is inside the .ready handler function. This is yet another reason to NEVER pass strings to setInterval(). Just pass an actual function reference and you won't have this problem because they are evaluated in the current scope.
    – jfriend00
    Commented Jan 26, 2013 at 5:22
  • Thanks, I was not aware of the need to NEVER pass strings to setInterval. Updated my answer.
    – Peter J
    Commented Feb 1, 2013 at 15:33
25

Similar to Peter J's solution (with a jQuery custom event)...

// Use the jquery-idle-detect.js script below
$(window).on('idle:start', function() {
  // Start your prefetch, etc. here...
});

$(window).on('idle:stop', function() {
  // Stop your prefetch, etc. here...
});

File jquery-idle-detect.js

(function($, $w) {
  // Expose configuration option
  // Idle is triggered when no events for 2 seconds
  $.idleTimeout = 2000;

  // Currently in idle state
  var idle = false;

  // Handle to idle timer for detection
  var idleTimer = null;

  // Start the idle timer and bind events on load (not DOM-ready)
  $w.on('load', function() {
    startIdleTimer();
    $w.on('focus resize mousemove keyup', startIdleTimer)
      .on('blur', idleStart) // Force idle when in a different tab/window
      ;
  ]);

  function startIdleTimer() {
    clearTimeout(idleTimer); // Clear prior timer

    if (idle) $w.trigger('idle:stop'); // If idle, send stop event
    idle = false; // Not idle

    var timeout = ~~$.idleTimeout; // Option to integer
    if (timeout <= 100)
      timeout = 100; // Minimum 100 ms
    if (timeout > 300000)
      timeout = 300000; // Maximum 5 minutes

    idleTimer = setTimeout(idleStart, timeout); // New timer
  }

  function idleStart() {
    if (!idle)
      $w.trigger('idle:start');
    idle = true;
  }

}(window.jQuery, window.jQuery(window)))
0
23

You can do it more elegantly with Underscore.js and jQuery:

$('body').on("click mousemove keyup", _.debounce(function(){
    // do preload here
}, 1200000)) // 20 minutes debounce
0
21

All the previous answers have an always-active mousemove handler. If the handler is jQuery, the additional processing jQuery performs can add up. Especially if the user is using a gaming mouse, as many as 500 events per second can occur.

This solution avoids handling every mousemove event. This result in a small timing error, but which you can adjust to your need.

function setIdleTimeout(millis, onIdle, onUnidle) {
    var timeout = 0;
    startTimer();

    function startTimer() {
        timeout = setTimeout(onExpires, millis);
        document.addEventListener("mousemove", onActivity);
        document.addEventListener("keydown", onActivity);
        document.addEventListener("touchstart", onActivity);
    }
    
    function onExpires() {
        timeout = 0;
        onIdle();
    }

    function onActivity() {
        if (timeout) clearTimeout(timeout);
        else onUnidle();
        //since the mouse is moving, we turn off our event hooks for 1 second
        document.removeEventListener("mousemove", onActivity);
        document.removeEventListener("keydown", onActivity);
        document.removeEventListener("touchstart", onActivity);
        setTimeout(startTimer, 1000);
    }
}

http://jsfiddle.net/9exz43v2/

6
  • 1
    Will this work automatically if placed on a page, or does it need to be inside a $(document).ready() wrapper? Thank you! Also, where is the portion which performs an action when the timer expires?
    – Oranges13
    Commented Aug 12, 2015 at 14:21
  • 1
    You can call this any time, even before document is ready. You pass a function 'callback' that will be called when the timer expires. Commented Aug 13, 2015 at 0:42
  • 1
    The $(startTimer) is equivalent to $(document).ready(startTimer), ensures that the DOM is ready before you hook the mousemove and keypress events. Commented Dec 9, 2015 at 18:02
  • 2
    +1 This is what I do - mousemove handlers contribute to sluggishness and reduced battery life, so only periodically turning it on is a great idea if you can afford the minor timing error. I usually use idle time detection for automatic session expiration warnings (eg "Are you still there?"), so I tend to have many minutes before a user goes "idle", in which case a small timing error is totally irrelevant.
    – goat
    Commented Feb 1, 2017 at 23:28
  • 2
    It is better to use "keydown" than "keypress" because arrow keys are not detected by the "keypress" event. So, if the user is navigating the page using the arrow keys, it will become Idle anyways.
    – aFerrer
    Commented Mar 14, 2019 at 20:01
20

My answer was inspired by vijay's answer, but is a shorter, more general solution that I thought I'd share for anyone it might help.

(function () { 
    var minutes = true; // change to false if you'd rather use seconds
    var interval = minutes ? 60000 : 1000; 
    var IDLE_TIMEOUT = 3; // 3 minutes in this example
    var idleCounter = 0;

    document.onmousemove = document.onkeypress = function () {
        idleCounter = 0;
    };

    window.setInterval(function () {
        if (++idleCounter >= IDLE_TIMEOUT) {
            window.location.reload(); // or whatever you want to do
        }
    }, interval);
}());

As it currently stands, this code will execute immediately and reload your current page after 3 minutes of no mouse movement or key presses.

This utilizes plain vanilla JavaScript and an immediately-invoked function expression to handle idle timeouts in a clean and self-contained manner.

1
  • document.onclick considers javascript functions using .trigger('click') which I wrote as automated. So it's not really a user interaction but it will reset the idleCounter in this case
    – Carmela
    Commented Jun 9, 2016 at 7:48
19

I had the same issue and I found a quite good solution.

I used jquery.idle and I only needed to do:

$(document).idle({
  onIdle: function(){
    alert('You did nothing for 5 seconds');
  },
  idle: 5000
})

See JsFiddle demo.

(Just for information: see this for back-end event tracking Leads browserload)

10
  • How can i stop this function, They stated an event idle:stop but I honestly dont know how to use this. I want that if i moved to next page (ajax based so only fragment of HTML page updated) then idle function stops. Did you know how to achieve this?
    – Mubasher
    Commented Jul 13, 2016 at 10:30
  • Here it says: "idle:stop": will stop and remove user tracking
    – DDan
    Commented Jul 14, 2016 at 0:51
  • I already have read but could not figure out how to use this, Could you help me ?
    – Mubasher
    Commented Jul 14, 2016 at 8:07
  • If you want it to fire only once, you can set the keepTracking option to false. If your want to reset you could try to reinitialize is. Here is a modified example which would fire only once: jsfiddle.net/f238hchm/12
    – DDan
    Commented Jul 14, 2016 at 8:49
  • No I do not fire once, keepTracking should be true, but on navigation to other page I want to stop this
    – Mubasher
    Commented Jul 14, 2016 at 10:00
18

If you are targeting a supported browser (Chrome or Firefox as of December 2018) you can experiment with the requestIdleCallback and include the requestIdleCallback shim for unsupported browsers.

3
  • And the leave the other browsers alone? Commented Nov 12, 2018 at 4:00
  • 1
    Shim cover all browsers. And this was the only answer! Other slow down answers is about mouse. The interactivity or CPU was only said as an example. How to detect CPU idle with a mouse solution?
    – user985399
    Commented Jul 9, 2019 at 13:49
  • 1
    This should be the only accepted answer. If the work you're doing could delay the main thread, it can cause hitches in animations, etc, so you should use requestIdleCallback (or requestAnimationFrame) where it's supported.
    – Coderer
    Commented Sep 1, 2021 at 9:35
14

You could probably hack something together by detecting mouse movement on the body of the form and updating a global variable with the last movement time. You'd then need to have an interval timer running that periodically checks the last movement time and does something if it has been sufficiently long since the last mouse movement was detected.

2
  • Important to note that the script will only be able to detect motion on the body of the page, not all user input. I don't think there's a way to get CPU or process info from javascript. Commented Mar 20, 2009 at 19:47
  • 2
    I took the liberty of implementing your idea in jQuery.
    – Peter J
    Commented Mar 20, 2009 at 21:14
14

I wrote a small ES6 class to detect activity and otherwise fire events on idle timeout. It covers keyboard, mouse and touch, can be activated and deactivated and has a very lean API:

const timer = new IdleTimer(() => alert('idle for 1 minute'), 1000 * 60 * 1);
timer.activate();

It does not depend on jQuery, though you might need to run it through Babel to support older browsers.

https://gist.github.com/4547ef5718fd2d31e5cdcafef0208096

8

(Partially inspired by the good core logic of Equiman's answer.)

sessionExpiration.js


sessionExpiration.js is lightweight yet effective and customizable. Once implemented, use in just one row:

sessionExpiration(idleMinutes, warningMinutes, logoutUrl);
  • Affects all tabs of the browser, not just one.
  • Written in pure JavaScript, with no dependencies. Fully client side.
  • (If so wanted.) Has warning banner and countdown clock, that is cancelled by user interaction.
  • Simply include the sessionExpiration.js, and call the function, with arguments [1] number of idle minutes (across all tabs) until user is logged out, [2] number of idle minutes until warning and countdown is displayed, and [3] logout url.
  • Put the CSS in your stylesheet. Customize it if you like. (Or skip and delete banner if you don't want it.)
  • If you do want the warning banner however, then you must put an empty div with ID sessExpirDiv on your page (a suggestion is putting it in the footer).
  • Now the user will be logged out automatically if all tabs have been inactive for the given duration.
  • Optional: You may provide a fourth argument (URL serverRefresh) to the function, so that a server side session timer is also refreshed when you interact with the page.

This is an example of what it looks like in action, if you don't change the CSS.

demo_image

7

Try this code. It works perfectly.

var IDLE_TIMEOUT = 10; //seconds
var _idleSecondsCounter = 0;

document.onclick = function () {
    _idleSecondsCounter = 0;
};

document.onmousemove = function () {
    _idleSecondsCounter = 0;
};

document.onkeypress = function () {
    _idleSecondsCounter = 0;
};

window.setInterval(CheckIdleTime, 1000);

function CheckIdleTime() {
    _idleSecondsCounter++;
    var oPanel = document.getElementById("SecondsUntilExpire");
    if (oPanel)
        oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
    if (_idleSecondsCounter >= IDLE_TIMEOUT) {
        alert("Time expired!");
        document.location.href = "SessionExpired.aspx";
    }
}
1
  • 3
    An explanation would be in order. E.g., why does it work perfectly? What is the idea/gist? How is it different from previous answers? Commented May 31, 2021 at 16:38
6
<script type="text/javascript">
    var idleTime = 0;
    $(document).ready(function () {
        //Increment the idle time counter every minute.
        idleInterval = setInterval(timerIncrement, 60000); // 1 minute

        //Zero the idle timer on mouse movement.
        $('body').mousemove(function (e) {
            //alert("mouse moved" + idleTime);
            idleTime = 0;
        });

        $('body').keypress(function (e) {
            //alert("keypressed"  + idleTime);
            idleTime = 0;
        });

        $('body').click(function() {
            //alert("mouse moved" + idleTime);
            idleTime = 0;
        });
    });

    function timerIncrement() {
        idleTime = idleTime + 1;
        if (idleTime > 10) { // 10 minutes

            window.location.assign("http://www.google.com");
        }
    }
</script>

I think this jQuery code is perfect one, though copied and modified from above answers!!

Do not forgot to include the jQuery library in your file!

1
  • A version of this is what I ended up using. I just pointed my window.location to a route that would unset my session variables and display a logout message. Commented Sep 20, 2021 at 22:37
5

Pure JavaScript with a properly set reset time and bindings via addEventListener:

(function() {

  var t,
    timeout = 5000;

  function resetTimer() {
    console.log("reset: " + new Date().toLocaleString());
    if (t) {
      window.clearTimeout(t);
    }
    t = window.setTimeout(logout, timeout);
  }

  function logout() {
    console.log("done: " + new Date().toLocaleString());
  }
  resetTimer();

  //And bind the events to call `resetTimer()`
  ["click", "mousemove", "keypress"].forEach(function(name) {
    console.log(name);
    document.addEventListener(name, resetTimer);
  });

}());
1
  • Could use a scroll listener and debouncing as well
    – kano
    Commented Sep 9, 2022 at 11:13
4

The problem with all these solutions, although correct, is they are impractical, when taking into account the session timeout valuable set, using PHP, .NET or in the Application.cfc file for ColdFusion developers.

The time set by the above solution needs to sync with the server-side session timeout. If the two do not sync, you can run into problems that will just frustrate and confuse your users.

For example, the server side session timeout might be set to 60 minutes, but the user may believe that he/she is safe, because the JavaScript idle time capture has increased the total amount of time a user can spend on a single page. The user may have spent time filling in a long form, and then goes to submit it. The session timeout might kick in before the form submission is processed.

I tend to just give my users 180 minutes, and then use JavaScript to automatically log the user out. Essentially, using some of the code above, to create a simple timer, but without the capturing mouse event part.

In this way my client side and server-side time syncs perfectly. There is no confusion, if you show the time to the user in your UI, as it reduces. Each time a new page is accessed in the CMS, the server side session and JavaScript timer are reset. Simple and elegant. If a user stays on a single page for more than 180 minutes, I figure there is something wrong with the page, in the first place.

1
  • 1
    Yep, that's why I'm only doing this after getting rid of server side sessions and loading everything from html files.
    – Dan Parker
    Commented Feb 22, 2016 at 23:02
3

You can use the below mentioned solution

var idleTime;
$(document).ready(function () {
         reloadPage();
        $('html').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
            clearTimeout(idleTime);
            reloadPage();
        });
});
function reloadPage() {
    clearTimeout(idleTime);
    idleTime = setTimeout(function () {
        location.reload();
    }, 3000);
}
3

I wrote a simple jQuery plugin that will do what you are looking for.

https://github.com/afklondon/jquery.inactivity

$(document).inactivity( {
    interval: 1000, // the timeout until the inactivity event fire [default: 3000]
    mouse: true, // listen for mouse inactivity [default: true]
    keyboard: false, // listen for keyboard inactivity [default: true]
    touch: false, // listen for touch inactivity [default: true]
    customEvents: "customEventName", // listen for custom events [default: ""]
    triggerAll: true, // if set to false only the first "activity" event will be fired [default: false]
});

The script will listen for mouse, keyboard, touch and other custom events inactivity (idle) and fire global "activity" and "inactivity" events.

1
  • Is there really a need for a delay, isn’t triggering a custom event from a custom event handler enough?
    – Hibou57
    Commented Sep 4, 2017 at 23:24
2

I have tested this code working file:

var timeout = null;
    var timee = '4000'; // default time for session time out.
    $(document).bind('click keyup mousemove', function(event) {

    if (timeout !== null) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(function() {
              timeout = null;
            console.log('Document Idle since '+timee+' ms');
            alert("idle window");
        }, timee);
    });
2

Surely you want to know about window.requestIdleCallback(), which queues a function to be called during a browser's idle periods.

You can see an elegant usage of this API in the Quicklink repo.

const requestIdleCallback = window.requestIdleCallback ||
  function (cb) {
    const start = Date.now();
    return setTimeout(function () {
      cb({
        didTimeout: false,
        timeRemaining: function () {
          return Math.max(0, 50 - (Date.now() - start));
        },
      });
    }, 1);
  };

The meaning of the code above is: if the browser supports requestIdleCallback (check the compatibility), uses it. If is not supported, uses a setTimeout(()=> {}, 1) as fallback, which should queue the function to be called at the end of the event loop.

Then you can use it like this:

requestIdleCallback(() => {...}, {
    timeout: 2000
  });

The second parameter is optional, you might want to set a timeout if you want to make sure the function is executed.

1
  • I dont think this is correct, "requestIdleCallback will schedule work when there is free time at the end of a frame, or when the user is inactive" .. so this may get triggered when the browser thinks there's some free time not only because of user idling
    – kofifus
    Commented Feb 20 at 3:53
2

Is it possible to have a function run every 10 seconds, and have that check a "counter" variable? If that's possible, you can have an on mouseover for the page, can you not?

If so, use the mouseover event to reset the "counter" variable. If your function is called, and the counter is above the range that you pre-determine, then do your action.

2

Here is the best solution I have found:

Fire Event When User is Idle

Here is the JavaScript:

idleTimer = null;
idleState = false;
idleWait = 2000;

(function ($) {

    $(document).ready(function () {

        $('*').bind('mousemove keydown scroll', function () {

            clearTimeout(idleTimer);

            if (idleState == true) {

                // Reactivated event
                $("body").append("<p>Welcome Back.</p>");
            }

            idleState = false;

            idleTimer = setTimeout(function () {

                // Idle Event
                $("body").append("<p>You've been idle for " + idleWait/1000 + " seconds.</p>");

                idleState = true; }, idleWait);
        });

        $("body").trigger("mousemove");

    });
}) (jQuery)
2

I use this approach, since you don't need to constantly reset the time when an event fires. Instead, we just record the time, and this generates the idle start point.

function idle(WAIT_FOR_MINS, cb_isIdle) {
    var self = this,
        idle,
        ms = (WAIT_FOR_MINS || 1) * 60000,
        lastDigest = new Date(),
        watch;
    //document.onmousemove = digest;
    document.onkeypress = digest;
    document.onclick = digest;

    function digest() {
       lastDigest = new Date();
    }

    // 1000 milisec = 1 sec
    watch = setInterval(function() {
        if (new Date() - lastDigest > ms && cb_isIdel) {
            clearInterval(watch);
            cb_isIdle();
        }

    }, 1000*60);
},
2

Based on the inputs provided by equiman:

class _Scheduler {
    timeoutIDs;

    constructor() {
        this.timeoutIDs = new Map();
    }

    addCallback = (callback, timeLapseMS, autoRemove) => {
        if (!this.timeoutIDs.has(timeLapseMS + callback)) {
            let timeoutID = setTimeout(callback, timeLapseMS);
            this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
        }

        if (autoRemove !== false) {
            setTimeout(
                this.removeIdleTimeCallback, // Remove
                10000 + timeLapseMS, // 10 secs after
                callback, // the callback
                timeLapseMS, // is invoked.
            );
        }
    };

    removeCallback = (callback, timeLapseMS) => {
        let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
        if (timeoutID) {
            clearTimeout(timeoutID);
            this.timeoutIDs.delete(timeLapseMS + callback);
        }
    };
}

class _IdleTimeScheduler extends _Scheduler {
    events = [
        'load',
        'mousedown',
        'mousemove',
        'keydown',
        'keyup',
        'input',
        'scroll',
        'touchstart',
        'touchend',
        'touchcancel',
        'touchmove',
    ];
    callbacks;

    constructor() {
        super();
        this.events.forEach(name => {
            document.addEventListener(name, this.resetTimer, true);
        });

        this.callbacks = new Map();
    }

    addIdleTimeCallback = (callback, timeLapseMS) => {
        this.addCallback(callback, timeLapseMS, false);

        let callbacksArr = this.callbacks.get(timeLapseMS);
        if (!callbacksArr) {
            this.callbacks.set(timeLapseMS, [callback]);
        } else {
            if (!callbacksArr.includes(callback)) {
                callbacksArr.push(callback);
            }
        }
    };

    removeIdleTimeCallback = (callback, timeLapseMS) => {
        this.removeCallback(callback, timeLapseMS);

        let callbacksArr = this.callbacks.get(timeLapseMS);
        if (callbacksArr) {
            let index = callbacksArr.indexOf(callback);
            if (index !== -1) {
                callbacksArr.splice(index, 1);
            }
        }
    };

    resetTimer = () => {
        for (let [timeLapseMS, callbacksArr] of this.callbacks) {
            callbacksArr.forEach(callback => {
                // Clear the previous IDs
                let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
                clearTimeout(timeoutID);

                // Create new timeout IDs.
                timeoutID = setTimeout(callback, timeLapseMS);
                this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
            });
        }
    };
}
export const Scheduler = new _Scheduler();
export const IdleTimeScheduler = new _IdleTimeScheduler();
1
  • Providing an example on how to use it would have been nice.
    – AymKdn
    Commented Jan 23, 2021 at 10:23
2

As simple as it can get, detect when the mouse moves only:

var idle = false;

document.querySelector('body').addEventListener('mousemove', function(e) {
    if(idle!=false)
        idle = false;
});

var idleI = setInterval(function()
{
    if(idle == 'inactive')
    {
        return;
    }

    if(idle == true)
    {
        idleFunction();
        idle = 'inactive';
        return;
    }

    idle = true;
}, 30000); // half the expected time. Idle will trigger after 60 s in this case.

function idleFuntion()
{
   console.log('user is idle');
}
1
  • What do you mean by "moves only"? In contrast to clicking? Or something else? Commented May 31, 2021 at 16:57
1

Here is an AngularJS service for accomplishing in Angular.

/* Tracks now long a user has been idle.  secondsIdle can be polled 
   at any time to know how long user has been idle. */
fuelServices.factory('idleChecker',['$interval', function($interval){
    var self = {
        secondsIdle: 0,
        init: function(){
            $(document).mousemove(function (e) {
                self.secondsIdle = 0;
            });
            $(document).keypress(function (e) {
                self.secondsIdle = 0;
            });
            $interval(function(){
                self.secondsIdle += 1;
            }, 1000)
        }
    }
    return self;
}]);

Keep in mind this idle checker will run for all routes, so it should be initialized in .run() on load of the angular app. Then you can use idleChecker.secondsIdle inside each route.

myApp.run(['idleChecker',function(idleChecker){
    idleChecker.init();
}]);
1

You could probably detect inactivity on your web page using the mousemove tricks listed, but that won't tell you that the user isn't on another page in another window or tab, or that the user is in Word or Photoshop, or WoW and just isn't looking at your page at this time.

Generally, I'd just do the prefetch and rely on the client's multi-tasking. If you really need this functionality, you do something with an ActiveX control in Windows, but it's ugly at best.

1

Debounce is actually a great idea! Here is a version for jQuery-free projects:

const derivedLogout = createDerivedLogout(30);
derivedLogout(); // It could happen that the user is too idle)
window.addEventListener('click', derivedLogout, false);
window.addEventListener('mousemove', derivedLogout, false);
window.addEventListener('keyup', derivedLogout, false);

function createDerivedLogout (sessionTimeoutInMinutes) {
    return _.debounce( () => {
        window.location = this.logoutUrl;
    }, sessionTimeoutInMinutes * 60 * 1000 )
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.