Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh page if there is no user activity for few seconds using javascript [duplicate]

Possible Duplicate:
How To Alter This Code So That It Only Redirects If There Is No Mouse Movement

I want to refresh a web page if there is no activity by the user using Javascript. User activity as in Key Press or mouse click.

like image 933
Scorpyon Avatar asked Jun 01 '12 11:06

Scorpyon


2 Answers

Here a basic example

(function(seconds) {
    var refresh,       
        intvrefresh = function() {
            clearInterval(refresh);
            refresh = setTimeout(function() {
               location.href = location.href;
            }, seconds * 1000);
        };

    $(document).on('keypress click', function() { intvrefresh() });
    intvrefresh();

}(15)); // define here seconds

This will refresh the page every 15 seconds without a keypress or a click event (but if you have same events defined elsewhere making a stopPropagation() this won't properly work because the event won't be able to reach the element)

like image 177
Fabrizio Calderan Avatar answered Oct 06 '22 00:10

Fabrizio Calderan


Create a timer (setTimeout) that will refresh the page, and every time there's a key press or mouse press, just restart the timer.

See this question for code that does most of what you want.

FWIW, here's F.Calderan's answer rewritten to:

  1. eliminate unnecessary closures
  2. separate the action from the repetition, by suppling the action as a callback

--

function setIdle(cb, seconds) {
    var timer; 
    var interval = seconds * 1000;
    function refresh() {
            clearInterval(timer);
            timer = setTimeout(cb, interval);
    };
    $(document).on('keypress click', refresh);
    refresh();
}

setIdle(function() {
    location.href = location.href;
}, 15);
like image 21
Alnitak Avatar answered Oct 06 '22 00:10

Alnitak