Javascript: Detect inactivity / idle time

PHOTO EMBED

Fri Aug 25 2023 18:34:07 GMT+0000 (Coordinated Universal Time)

Saved by @marcopinero #javascript

<!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>
content_copyCOPY