How can I automatically reload a webpage, if there have been no activity on the page for a given period of time?
-
Perhaps http://stackoverflow.com/questions/3729959/robust-auto-refresh-web-page is related? – Raghuram Jan 10 '11 at 05:53
17 Answers
This can be accomplished without javascript, with this metatag:
<meta http-equiv="refresh" content="5" >
where content ="5" are the seconds that the page will wait until refreshed.
But you said only if there was no activity, what kind for activity would that be?

- 10,519
- 8
- 40
- 45

- 26,114
- 9
- 67
- 76
-
4No Activity means End User is not on desk or surfing some other site. No Mouse/KB activity on site which I am referring for. – Umar Adil Jan 10 '11 at 07:02
-
2great answer, thought this had to be done with `setInterval`, so glad to know this exists! – tim peterson Jan 17 '14 at 18:18
-
16upvoted even though this is not the answer because it does not capture activity, however this question was at the top of Google search results when simply looking for javascript refresh. So, if you are simply looking to have the page automatically refresh on a set interval, this is the way to go. – Jimmy Bosse Sep 22 '14 at 12:37
-
-
This trick is not changing scrollbar position after page refresh. Therefore I prefer to use this one. – Mojtaba Rezaeian Mar 15 '16 at 18:53
-
While this answer provides working code for a similar case scenario, it does NOT answer the original question whatsoever, in fact it just asks for further clarification. – Tarquin Jul 27 '17 at 05:00
-
3this is not answering the question. If there is an activity it will reload anyway – Braian Mellor Oct 31 '17 at 14:24
-
This meta method blinks a lot more than this other way I prefer: `` – Manu Järvinen Sep 22 '18 at 16:31
-
@Developer Because it's exactly what you want when you don't care about activity - i.e. a static page which gets updated from an external source. – stuartd Nov 11 '19 at 16:17
If you want to refresh the page if there is no activity then you need to figure out how to define activity. Let's say we refresh the page every minute unless someone presses a key or moves the mouse. This uses jQuery for event binding:
<script>
var time = new Date().getTime();
$(document.body).bind("mousemove keypress", function(e) {
time = new Date().getTime();
});
function refresh() {
if(new Date().getTime() - time >= 60000)
window.location.reload(true);
else
setTimeout(refresh, 10000);
}
setTimeout(refresh, 10000);
</script>

- 5,864
- 3
- 30
- 32
-
5why would you set the interval to 10000 if it is calculating using 60000? For at least 5 turns it will be false? – Scary Wombat Jun 07 '17 at 00:56
-
3The reason why the interval is lower than the inactivity time is that you want to check the inactivity time in a much higher frequency than the actual inactivity time. For example if the inactivity time is 1 minute and the interval is 1 minute, if the user moved the mouse after 1 second and then stopped, the refresh will only occur after 2 minutes. The lower the interval the more accurate the refresh time will be. – Derorrist Nov 20 '19 at 10:23
I have built a complete javascript solution as well that does not require jquery. Might be able to turn it into a plugin. I use it for fluid auto-refreshing, but it looks like it could help you here.
// Refresh Rate is how often you want to refresh the page
// bassed off the user inactivity.
var refresh_rate = 200; //<-- In seconds, change to your needs
var last_user_action = 0;
var has_focus = false;
var lost_focus_count = 0;
// If the user loses focus on the browser to many times
// we want to refresh anyway even if they are typing.
// This is so we don't get the browser locked into
// a state where the refresh never happens.
var focus_margin = 10;
// Reset the Timer on users last action
function reset() {
last_user_action = 0;
console.log("Reset");
}
function windowHasFocus() {
has_focus = true;
}
function windowLostFocus() {
has_focus = false;
lost_focus_count++;
console.log(lost_focus_count + " <~ Lost Focus");
}
// Count Down that executes ever second
setInterval(function () {
last_user_action++;
refreshCheck();
}, 1000);
// The code that checks if the window needs to reload
function refreshCheck() {
var focus = window.onfocus;
if ((last_user_action >= refresh_rate && !has_focus && document.readyState == "complete") || lost_focus_count > focus_margin) {
window.location.reload(); // If this is called no reset is needed
reset(); // We want to reset just to make sure the location reload is not called.
}
}
window.addEventListener("focus", windowHasFocus, false);
window.addEventListener("blur", windowLostFocus, false);
window.addEventListener("click", reset, false);
window.addEventListener("mousemove", reset, false);
window.addEventListener("keypress", reset, false);
window.addEventListener("scroll", reset, false);
document.addEventListener("touchMove", reset, false);
document.addEventListener("touchEnd", reset, false);

- 3,250
- 3
- 24
- 22
-
4This is great. Wish you got upvoted more here. Not using JQuery gets major bonus points. – Echiban Feb 24 '16 at 05:08
-
1* great / many thanks * does this account for detecting touch events? – DotDotJames Jun 28 '18 at 20:52
-
1Hmm you know I am not sure. When I created it I did not have a lot of experience with iPhone or iPads. – User128848244 Jun 30 '18 at 02:02
-
1Hero! This is perfect thanks. I have my PHP sessions set to expire after an hour, and this is set to refresh a little over an hour. I think this should accomplish the logout after inactivity functionality i'm after. – Tspesh Dec 26 '18 at 19:10
-
Please could you provide a solution if I want to pause a timer not reset? – karjaubayev Aug 05 '20 at 06:41
-
Thanks, why does the code calls reset() after reload()? Would it ever be executed? – Itamar K. Nov 15 '22 at 11:57
<script type="text/javascript">
var timeout = setTimeout("location.reload(true);",600000);
function resetTimeout() {
clearTimeout(timeout);
timeout = setTimeout("location.reload(true);",600000);
}
</script>
Above will refresh the page every 10 minutes unless resetTimeout() is called. For example:
<a href="javascript:;" onclick="resetTimeout();">clicky</a>

- 1,447
- 1
- 19
- 38

- 67,283
- 14
- 105
- 142
Based on the accepted answer of arturnt. This is a slightly optimized version, but does essentially the same thing:
var time = new Date().getTime();
$(document.body).bind("mousemove keypress", function () {
time = new Date().getTime();
});
setInterval(function() {
if (new Date().getTime() - time >= 60000) {
window.location.reload(true);
}
}, 1000);
Only difference is that this version uses setInterval
instead of setTimeout
, which makes the code more compact.

- 1,835
- 1
- 23
- 38
-
why would you set the interval to `1000` if it is calculating using `60000`? – Scary Wombat Jun 07 '17 at 00:54
-
3The interval is 1.000 because it checks every second if the mouse has been moved. The 60.000 then is used to determine if the last mouse move has happened at least a minute ago. – Hannes Sachsenhofer Jun 07 '17 at 05:53
var bd = document.getElementsByTagName('body')[0];
var time = new Date().getTime();
bd.onmousemove = goLoad;
function goLoad() {
if(new Date().getTime() - time >= 1200000) {
time = new Date().getTime();
window.location.reload(true);
}else{
time = new Date().getTime();
}
}
Each time you move the mouse it will check the last time you moved the mouse. If the time interval is greater than 20' it will reload the page, else it will renew the last-time-you-moved-the-mouse.
use JavaScript setInterval
method:
setInterval(function(){ location.reload(); }, 3000);

- 10,744
- 13
- 61
- 94

- 91
- 1
- 12
Auto reload with target of your choice. In this case target is _self
set to itself,but you could change the reload page by simply changing the window.open('self.location', '_self');
code to something like this examplewindow.top.location="window.open('http://www.YourPageAdress.com', '_self'";
.
With a confirmation ALERT message:
<script language="JavaScript">
function set_interval() {
//the interval 'timer' is set as soon as the page loads
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
itimer=setInterval("auto_logout()",timeoutMins);
atimer=setInterval("alert_idle()",timeout1Mins);
}
function reset_interval() {
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scrolling
//first step: clear the existing timer
clearInterval(itimer);
clearInterval(atimer);
//second step: implement the timer again
itimer=setInterval("auto_logout()",timeoutMins);
atimer=setInterval("alert_idle()",timeout1Mins);
}
function alert_idle() {
var answer = confirm("Session About To Timeout\n\n You will be automatically logged out.\n Confirm to remain logged in.")
if (answer){
reset_interval();
}
else{
auto_logout();
}
}
function auto_logout() {
//this function will redirect the user to the logout script
window.open('self.location', '_self');
}
</script>
Without confirmation alert:
<script language="JavaScript">
function set_interval() {
//the interval 'timer' is set as soon as the page loads
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
itimer=setInterval("auto_logout()",timeoutMins);
}
function reset_interval() {
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scrolling
//first step: clear the existing timer
clearInterval(itimer);
clearInterval(atimer);
//second step: implement the timer again
itimer=setInterval("auto_logout()",timeoutMins);
}
function auto_logout() {
//this function will redirect the user to the logout script
window.open('self.location', '_self');
}
</script>
Body code is the SAME for both solutions:
<body onLoad="set_interval(); document.form1.exp_dat.focus();" onKeyPress="reset_interval();" onmousemove="reset_interval();" onclick="reset_interval();" onscroll="reset_interval();">

- 973
- 1
- 9
- 33
-
this is not answering the question. If there is an activity it will reload anyway. – Braian Mellor Oct 31 '17 at 14:23
-
1Your right, I did not read the entire question. Okay now it is EDITED with the correct answer. – SeekLoad Nov 01 '17 at 13:51
-
I taked out the -1 and added +10 for making a better answer! thanks – Braian Mellor Nov 01 '17 at 13:59
-
I also have a second answer that works, But right now I fine tune this answer as it can be better with a targeted solution as I edited it now to. – SeekLoad Nov 01 '17 at 14:01
-
1I gave 3 answers now for the same solution, depending what feels more easy to apply or fits the needs. All 3 solutions have with or without confirmation or alert. I answered with 3 answers since the 3 answers are with different codes and it would be too long to have it all solutions together in one answer. Also I added explanations to how to edit the codes once used. All answers of course work perfectly... It was tested before I put them here. – SeekLoad Nov 01 '17 at 17:12
I came up with a slightly different solution, because I found that setInterval
isn't really accurate, see: setInterval timing slowly drifts away from staying accurate
// Based on https://stackoverflow.com/a/15279599
// Refresh Rate is how often you want to refresh the page
// based off the user inactivity (in seconds).
var refresh_after = 20;
var last_user_action = new Date();
// Reset the Timer on users last action
function reset() {
last_user_action = new Date();
}
// Countdown that executes every second.
setInterval(function () {
refreshCheck();
}, 1000);
// The code that checks if the window needs to reload
function refreshCheck() {
var expire_time = new Date(last_user_action);
expire_time.setSeconds(expire_time.getSeconds() + refresh_after);
now = new Date();
if (now.getTime() >= expire_time.getTime() && document.readyState == "complete") {
window.location.href = window.location.href; // We do this to discard the POST data.
}
}
window.addEventListener("click", reset, false);
window.addEventListener("mousemove", reset, false);
window.addEventListener("keypress", reset, false);
window.addEventListener("scroll", reset, false);
document.addEventListener("touchMove", reset, false);
document.addEventListener("touchEnd", reset, false);

- 13
- 2
Yes dear,then you have to use Ajax technology. to changes contents of particular html tag:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Ajax Page</title>
<script>
setInterval(function () { autoloadpage(); }, 30000); // it will call the function autoload() after each 30 seconds.
function autoloadpage() {
$.ajax({
url: "URL of the destination page",
type: "POST",
success: function(data) {
$("div#wrapper").html(data); // here the wrapper is main div
}
});
}
</script>
</head>
<body>
<div id="wrapper">
contents will be changed automatically.
</div>
</body>
</html>
I would consider activity
to be whether or not the user is focused on the window. For example, when you click from one window to another (e.g. Google Chrome to iTunes, or Tab 1 to Tab 2 within an internet browser), the webpage can send a callback saying "Im out of focus!" or "Im in focus!". One could use jQuery to harness this possible lack of activity to do whatever they wanted. If I were in your position, I would use the following code to check for focus every 5 seconds, etc and reload if no focus.
var window_focus;
$(window).focus(function() {
window_focus = true;
}).blur(function() {
window_focus = false;
});
function checkReload(){
if(!window_focus){
location.reload(); // if not focused, reload
}
}
setInterval(checkReload, 5000); // check if not focused, every 5 seconds

- 183
- 3
- 9
With on page confirmation text instead of alert
Since this is another method to auto load if inactive I give it a second answer. This one is more simple and easier to understand.
With reload confirmation on the page
<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5100; // 5,1 seconds
var warnPeriod = 5000; // 5 seconds
// Warning period should always be a bit shorter then time period
function promptForClose() {
autoCloseDiv.style.display = 'block';
autoCloseTimer = setTimeout("definitelyClose()", warnPeriod);
}
function autoClose() {
autoCloseDiv.style.display = 'block'; //shows message on page
autoCloseTimer = setTimeout("definitelyClose()", timePeriod); //starts countdown to closure
}
function cancelClose() {
clearTimeout(autoCloseTimer); //stops auto-close timer
autoCloseDiv.style.display = 'none'; //hides message
}
function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("promptForClose()", timePeriod); //restarts timer from 0
}
function definitelyClose() {
// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or this: window.open('http://www.YourPageAdress.com', '_self');
// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');
window.top.location=self.location;
}
-->
</script>
Confirmation box when using with on page confirmation
<div class="leftcolNon">
<div id='autoCloseDiv' style="display:none">
<center>
<b>Inactivity warning!</b><br />
This page will Reloads automatically unless you hit 'Cancel.'</p>
<input type='button' value='Load' onclick='definitelyClose();' />
<input type='button' value='Cancel' onclick='cancelClose();' />
</center>
</div>
</div>
Body codes for both are the SAME
<body onmousedown="resetTimeout();" onmouseup="resetTimeout();" onmousemove="resetTimeout();" onkeydown="resetTimeout();" onload="timeoutObject=setTimeout('promptForClose()',timePeriod);">
NOTE: If you do not want to have the on page confirmation, use Without confirmation
<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5000; // 5 seconds
function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("definitelyClose()", timePeriod); //restarts timer from 0
}
function definitelyClose() {
// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or this: window.open('http://www.YourPageAdress.com', '_self');
// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');
window.top.location=self.location;
}
-->
</script>

- 973
- 1
- 9
- 33
-
I gave 3 answers now for the same solution, depending what feels more easy to apply or fits the needs. All 3 solutions have with or without confirmation or alert. I answered with 3 answers since the 3 answers are with different codes and it would be too long to have it all solutions together in one answer. Also I added explanations to how to edit the codes once used. All answers of course work perfectly... It was tested before I put them here. – SeekLoad Nov 01 '17 at 17:13
And finally the most simple solution:
With alert confirmation:
<script type="text/javascript">
// Set timeout variables.
var timoutWarning = 3000; // Display warning in 1Mins.
var timoutNow = 4000; // Timeout in 2 mins.
var warningTimer;
var timeoutTimer;
// Start timers.
function StartTimers() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
}
// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(timeoutTimer);
StartTimers();
$("#timeout").dialog('close');
}
// Show idle timeout warning dialog.
function IdleWarning() {
var answer = confirm("Session About To Timeout\n\n You will be automatically logged out.\n Confirm to remain logged in.")
if (answer){
ResetTimers();
}
else{
IdleTimeout();
}
}
// Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
function IdleTimeout() {
window.open(self.location,'_top');
}
</script>
Without alert confirmation:
<script type="text/javascript">
// Set timeout variables.
var timoutWarning = 3000; // Display warning in 1Mins.
var timoutNow = 4000; // Timeout in 2 mins.
var warningTimer;
var timeoutTimer;
// Start timers.
function StartTimers() {
warningTimer = setTimeout(timoutWarning);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
}
// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(timeoutTimer);
StartTimers();
$("#timeout").dialog('close');
}
// Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
function IdleTimeout() {
window.open(self.location,'_top');
}
</script>
Body code is the SAME for both solutions
<body onload="StartTimers();" onmousemove="ResetTimers();" onKeyPress="ResetTimers();">

- 973
- 1
- 9
- 33
-
I gave 3 answers now for the same solution, depending what feels more easy to apply or fits the needs. All 3 solutions have with or without confirmation or alert. I answered with 3 answers since the 3 answers are with different codes and it would be too long to have it all solutions together in one answer. Also I added explanations to how to edit the codes once used. All answers of course work perfectly... It was tested before I put them here. – SeekLoad Nov 01 '17 at 17:13
Using LocalStorage to keep track of the last time of activity, we can write the reload function as follows
function reloadPage(expiryDurationMins) {
const lastInteraction = window.localStorage.getItem('lastinteraction')
if (!lastInteraction) return // no interaction recorded since page load
const inactiveDurationMins = (Date.now() - Number(lastInteraction)) / 60000
const pageExpired = inactiveDurationMins >= expiryDurationMins
if (pageExpired) window.location.reload()
}
Then we create an arrow function which saves the last time of interaction in milliseconds(String)
const saveLastInteraction = () => window.localStorage.setItem('last', Date.now().toString())
We will need to listen to the beforeunload
event in the browser to clear our lastinteraction
record so we don't get stuck in an infinite reload loop.
window.addEventListener('beforeunload', () => window.localStorage.removeItem('lastinteraction'))
The user activity events we will need to monitor would be mousemove
and keypress
. We store the last interaction time when the user moves the mouse or presses a key on the keyboard
window.addEventListener('mousemove', saveLastInteraction)
window.addEventListener('keypress', saveLastInteraction)
To set up our final listener, we will use the load
event.
On page load, we use the setInterval
function to check if the page has expired after a certain period.
const expiryDurationMins = 1
window.addEventListener('load', setInterval.bind(null, reloadPage.bind(null, expiryDurationMins), 1000))

- 70
- 1
- 5
I am doing it like this:
let lastActionTaken = new Date().getTime();
function checkLastAction() {
let now = new Date().getTime();
if (now - lastActionTaken > 1000 * 60 * 60) window.location.reload();
else lastActionTaken = now;
}
window.addEventListener("mousemove", checkLastAction);
window.addEventListener("touchstart", checkLastAction);
window.addEventListener("keydown", checkLastAction);
This will reload the page as soon as the user moves their mouse, hits a key or touches a touchscreen if it has been inactive for 1 hour. Also, this takes care of the focus
as well, so if a user is moving their mouse in a different program and then come back to this window
it will reload, which is good because the point is to not have old data being shown.

- 882
- 10
- 16
Many of these other answers either don't answer the main part of the question "with no activity", or they are incredibly, unnecessarily complex. I have taken the accepted answer (here: https://stackoverflow.com/a/4644315/9008140 ) and modified it to take advantage of the fact you can assign timers to variables. This allows us to get rid of the second timer, as well as the timestamp.
/**
* create a timer that refreshes the page after the number of
minutes has passed without user interaction.
* Moving the mouse or pressing a key on the current page will start
the timer over.
* @param {any} minutes
*/
var refreshTimer;
function setPageRefreshTimer(minutes) {
var refreshInterval = minutes * 60 * 1000; //interval is in milliseconds. We refresh every x minutes.
$(document.body).bind("mousemove keypress", function (e) {
if (refreshTimer != null && refreshTimer != undefined) {
window.clearTimeout(refreshTimer);
}
refreshTimer = window.setTimeout(function () { window.location.reload(true); }, refreshInterval);
});
refreshTimer = window.setTimeout(function () { window.location.reload(true); }, refreshInterval);
}
This sample code will refresh based on a passed in parameter in minutes, with an accuracy as great as a javascript timer can be. In testing, always less than a second. I created this as a function but you can pull it into your page if you wish.

- 1,941
- 12
- 27
This task is very easy use following code in html header section
<head> <meta http-equiv="refresh" content="30" /> </head>
It will refresh your page after 30 seconds.

- 350
- 3
- 4
-
2
-
Yes dear,then you have to use Ajax technology. to changes contents of particular html tag – FAISAL Dec 12 '13 at 14:30
-
-
1This method you answered does not answer the question, since the question is about how to reload if there is NO activate on the page, and your solution will automatically force reload even if there is an activity on the page. The answer searched here is how to make it reload if there is no mouse or keyboard use wile being on the page within an amount of time. NOTE: I am telling you this because I myself did the same mistake when I answered last time, so I changed my answer to fit the question. – SeekLoad Nov 01 '17 at 17:16