How to Detect Idle Time in JavaScript

The idle time is the time that the user has no interaction with the web-page. It can be mouse movement, page click or when the user uses the keyboard. The idle time can be detected using either vanilla JavaScript or jQuery code.

Vanilla JavaScript

You can use vanilla JavaScript to detect the idle time:

Vanilla JavaScript to detect the idle time
let inactivityTime = function () { let time; window.onload = resetTimer; document.onmousemove = resetTimer; document.onkeypress = resetTimer; function logout() { console.log("You are now logged out.") } function resetTimer() { clearTimeout(time); time = setTimeout(logout, 2000) } }; inactivityTime(); console.log('Please wait...');

And initialize the function where you need it:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <script>
      let inactivityTime = function() {
        let time;
        window.onload = resetTimer;
        document.onmousemove = resetTimer;
        document.onkeypress = resetTimer;
        function logout() {
          alert("You are now logged out.")
        }
        function resetTimer() {
          clearTimeout(time);
          time = setTimeout(logout, 2000)
        }
      };
      window.onload = function() {
        inactivityTime();
      }
    </script>
  </body>
</html>

You can also add more DOM events if it is required. The most used ones are the following:

Vanilla JavaScript to detect the idle time
let inactivityTime = function () { let time; window.onload = resetTimer; document.onload = resetTimer; document.onmousemove = resetTimer; document.onmousedown = resetTimer; // touchscreen presses document.ontouchstart = resetTimer; document.onclick = resetTimer; // touchpad clicks document.onkeypress = resetTimer; document.addEventListener('scroll', resetTimer, true); // improved; see comments function logout() { console.log("You are now logged out.") } function resetTimer() { clearTimeout(time); time = setTimeout(logout, 2000) } }; inactivityTime(); console.log('Please wait...');

To register the desired events use an array:

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

DOM Events

HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document. Events collaborate with functions. The function will not be invoked before the event occurs (such as when a user clicks any button).