How to Detect Idle Time in JavaScript ?

The idle time is the time that the user doesn’t interact with a web-page. This interaction can be either moving the mouse, clicking on the page or using the keyboard. This time can be detected to execute certain events that may need to occur after a certain period of idle time.

Method 1: Using JavaScript: For the implementation, two functions are created, one is the function that resets the timer whenever user interaction is detected and the other is the function that would be executed periodically during the time the user is idle. The reset function consists of the setInterval() function, which is used to create a new interval that will repeatedly invoke another function. The timer created is assigned to a variable that will be used to clear out the old-timer whenever this function is called again on user interaction.

This function is invoked by binding it to the events that cause interaction to the page. These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress.

The other function which will be invoked when the user is idle can be used to keep track of the time and perform actions when the user has been inactive for a longer time. An example of this would be to log out the user when inactive for more than a specified time.

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to detect idle
        time in JavaScript ?
    </title>
</head>
  
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to detect idle time in
        JavaScript elegantly?
    </b>
      
    <p>
        The timer will be incremented every
        second to denote the idle time.
        Interaction with the mouse or
        keyboard will reset and hide the timer.
    </p>
  
    <p class="timertext" 
        style="font-size: 1.5rem;">
        You are idle for
        <span class="secs"></span> seconds.
    </p>
  
    <script type="text/javascript">
        let timer, currSeconds = 0;
  
        function resetTimer() {
  
            /* Hide the timer text */
            document.querySelector(".timertext")
                    .style.display = 'none';
  
            /* Clear the previous interval */
            clearInterval(timer);
  
            /* Reset the seconds of the timer */
            currSeconds = 0;
  
            /* Set a new interval */
            timer = 
                setInterval(startIdleTimer, 1000);
        }
  
        // Define the events that
        // would reset the timer
        window.onload = resetTimer;
        window.onmousemove = resetTimer;
        window.onmousedown = resetTimer;
        window.ontouchstart = resetTimer;
        window.onclick = resetTimer;
        window.onkeypress = resetTimer;
  
        function startIdleTimer() {
              
            /* Increment the
                timer seconds */
            currSeconds++;
  
            /* Set the timer text
                to the new value */
            document.querySelector(".secs")
                .textContent = currSeconds;
  
            /* Display the timer text */
            document.querySelector(".timertext")
                .style.display = 'block';
        }
    </script>
</body>
  
</html>

chevron_right


Output:

  • After Interacting with the page:
    interacting
  • After Not interacting with the page:
    idle

Method 2: Using jQuery: It similar to the above method, however here a new timer is not created every time when user interaction is detected. Instead, the running timer is reset to 0 whenever user interaction is detected. For the implementation, two functions are created, one is the function that resets the timer to 0 whenever user interaction is detected and the other is the function that would be executed periodically during the time the user is idle.
A new variable is defined which will globally represent the current time of the idle timer.

Using the document.ready() event, a timer with the setInterval() function is created which repeatedly invokes another function that handles what will happen when the user is idle for a specified time. The reset function consists of a simple statement that will change the value of the timer variable to 0, effectively resetting the current idle time. This function is invoked by binding it to the events that cause interaction to the page. These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to detect idle
        time in JavaScript ?
    </title>
      
        <script src=
    </script>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to detect idle time in
        JavaScript elegantly?
    </b>
      
    <p>
        The timer will be incremented every 
        second to denote the idle time.
        Interaction with the mouse or keyboard
        will reset and hide the timer.
    </p>
  
    <p class="timertext"
        style="font-size: 1.5rem;">
        You are idle for
        <span class="secs"></span> seconds.
    </p>
      
    <script type="text/javascript">
        var currSeconds = 0;
          
        $(document).ready(function() {
  
            /* Increment the idle time
                counter every second */
            let idleInterval =
                setInterval(timerIncrement, 1000);
  
            /* Zero the idle timer
                on mouse movement */
            $(this).mousemove(resetTimer);
            $(this).keypress(resetTimer);
        });
  
        function resetTimer() {
  
            /* Hide the timer text */
            document.querySelector(".timertext")
                .style.display = 'none';
              
            currSeconds = 0;
        }
  
        function timerIncrement() {
            currSeconds = currSeconds + 1;
  
            /* Set the timer text to
                the new value */
            document.querySelector(".secs")
                .textContent = currSeconds;
  
            /* Display the timer text */
            document.querySelector(".timertext")
                .style.display = 'block';
        }
    </script>
</body>
  
</html>

chevron_right


Output:

  • After Interacting with the page:
    interacting-2
  • After Not interacting with the page:
    idle-2

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.