Domanda

This code is similar in nature to that of:

Run setTimeout only when tab is active

However, what I'm trying to accomplish here is a reset of this 10s timer upon any user activity on the document. For my testing I'm currently using keyup, but I need to also make this work with moving the mouse over any element in the document, etc..

Here is the code, see commented code for potential changes I will be doing, I left them commented as I have found them to not really work:

$(function(){
//var keyed = false;
function myFunction() {
    window.location.href="/backoffice/logout.jsp?forceClose=true";
}

(function() {
    //Just under 15 min in milliseconds
    //var time = 895000,
    var time = 10000,
        delta = 100,
        tid;

    tid = setInterval(function() {
        if ( window.blurred ) { return; }    
        time -= delta;
        //if ( keyed ) { 
        //  time = 10000; 
        //} 
        //keyed = false;
        if ( time <= 0 ) {
            clearInterval(tid);
            myFunction(); // time passed - do your work
        }        
    }, delta);
})();
//window.onkeyup = function() { keyed = true; };
window.onblur = function() { window.blurred = true; };
window.onfocus = function() { window.blurred = false; };
});

Of course I don't understand how to get this to work in practice, but hopefully my thought process is clear, I am trying to make it so that the active tab will also listen for keypresses or mouse clicks (maybe even mouse movement), and reset the timer if that is the case.

Does anyone have any advice in accomplishing this?

È stato utile?

Soluzione 2

function myFunction() {
    //window.location.href="/backoffice/logout.jsp?forceClose=true";
    alert('hello world');
}

function listener() {

     window.time = 10000,
     delta = 100,

    window.tid = setInterval(function() {   
        window.time -= delta;
        console.log(window.time);
        if ( time <= 0 ) {
            clearInterval(window.tid);
            myFunction(); // time passed - do your work
        }        
    }, delta);

};

    listener();

     $(document).on('keyup keypress blur change mousemove',function(){
        clearInterval(window.tid);
        listener();
    });

});

Altri suggerimenti

You can just restart the timer on any action, like this:

var tid = null;

function startTimeout() {
  tid = setTimeout( // your code);
}

window.onkeyup = function() {
   tid && clearTimeout(tid);
   tid = startTimeout();
}

When using setTimeout instead of setInterval, you have to remember to restart the timer after completion again:

function startTimeout() {
  tid = setTimeout(function(){ 
    // some code

    // start timer again!
    startTimeout();
  }, 10000);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top