How to refresh a page if there is no user activity in a few seconds using javascript

Possible duplicate:
How to change this code so that it is redirected if there is no mouse movement

I want to refresh a webpage if the user is not using Javascript. User activity, as in Key. Click or click.

+7
source share
2 answers

Here is 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 pressing a key or click event (but if you have the same events that are defined elsewhere by creating stopPropagation() , this will not work properly because the event cannot reach the element)

+12
source

Create a timer ( setTimeout ) that refreshes the page, and each time you press a key or press a mouse, simply restart the timer.

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

FWIW, here the answer of F. Calderan is rewritten to:

  • eliminate unnecessary short circuits
  • separate an action from repeating by serving 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); 
+5
source

All Articles