JS Timeout Event

APD Toronto
APD Toronto used Ask the Experts™
on
Hi Experts,

If anyone can tell me how I can code a JS (or jQuery) event for timeout, let say for 10 minutes if there is no activity to do a self.location = 'timeout.html'

However, when the user click something or types, the timer to go back to 10 minutes.

Thank you
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2010
Commented:
Here is a simple example using setTimeout() and clearTimeout():

$(document).ready(function() {
  var timer;

  function setTimer() {
    timer = setTimeout(function() {
      alert("Time Is Up!");
    }, 5000);
  }

  $('form :input').on('keyup', function() {
    clearTimeout(timer);
    setTimer();
  });
  
  setTimer();
});

Open in new window


So, every time a keyup event occurs, the timer gets reset.  If you have other types of elements on your form (drop down, checkbox, etc), you will also need to look for the related events (such as the change event).
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
Megan has presented a good example - here is another approach for reference. Rather than reseting the timer use setInterval and check a flag on each timeout.
<script>
$(function() {
  var TIMEOUT = 10,    // SET TO NUMBER OF INTERVALS TO CHECK
      INTERVAL = 60000, // 1 MINUTE INTERVALS
      tickCount = 0,   
      timeoutURL = 't2778.timeout.html', // URL TO REDIRECT TO ON TIMEOUT
      timer = setInterval(checkTimer, INTERVAL);

  $(this).mousemove(function() {
    tickCount = 0;
  });
  $(this).keypress(function() {
    tickCount = 0;
  });

  function checkTimer() {
    if (++tickCount >= TIMEOUT) {
      clearInterval(timer);
      window.location = timeoutURL;
    }
  }
});
</script>

Open in new window

You can see it working here
APD TorontoSoftware Developer

Author

Commented:
Julian, with $(this) will that consider all activities and not this form element?
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Yes - at the global level $(this) is analogous to $(document).

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial