views:

81

answers:

2

I have a web page, using jQuery and javaScript, and I would like to find out if and when to put the page to sleep. As a number of the tasks are background processes I need to put them to sleep if nothing is happening on the page. i.e. the user is working on another screen or not on his PC full stop

A: 

Perhaps a timeout function would work. It would have to check periodically whether any events you care about have occurred, and so decide whether to put the page "to sleep."

Eric Mickelsen
+2  A: 

The easiest way is to set a timer that is reset on several events based on user interaction with the page. A very basic example would be:

var timeout;    
var awake = true;
function resetTimer ()
{
    awake = true;
    window.clearTimeout(timeout);
    timeout = window.setTimeout(function () 
    {
        awake = false;
    }, 36000); // Set the timer for 5 minutes
}
document.documentElement.onfocus = document.documentElement.onmouseover = function ()
{
    if (!awake)
        runRequests(); // Replace any stale data
    resetTimer();
}

In the requests for the data, you would check the state of the awake variable and if it's false, return out of the function. When the user interacts with the page again, the necessary data would be refreshed and the awake variable set to true again.

Andy E