Search code examples
javascriptjquerytimeoutkeypress

Timeout time counting does not detect input field


I write method to reset timeout on mouse click, keyup and keypress, but I just realised that it does not check on input field so when I'm actively typing in a field it will timeout. Here is my code:

var idleInterval = setInterval(timerIncrement, 10000); 
var idleTime = 0;
$(document).ready(function () {
  //Increment the idle time counter every minute.
  //Zero the idle timer on mouse movement.
  $(this).mousemove(function (e) {
    idleTime = 0;
  });
  $(this).keypress(function (e) {
    idleTime = 0;
  });
  $(this).keyup(function (e) {
    idleTime = 0;
  });
});

function timerIncrement() {
  idleTime = idleTime + 1;
  if (idleTime > 4) {
    window.location.replace('/timeout.aspx');
  }
}

Solution

  • You should have all the code inside the document.ready() function.

    $(document).ready(function() {
        var idleInterval = setInterval(timerIncrement, 10000);
        var idleTime = 0;
    
        $(document).on('keyup', function() {
            console.log('Keyup Detected');
            idleTime = 0;
        });
    
        function timerIncrement() {
            idleTime++;
    
            if (idleTime > 4)
                window.location.replace('/timeout.aspx');
        }
    });