Reputation: 63
I'm using the following javascript to refresh a div on a page every 30 seconds:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(document).ready(function(){
$.ajaxSetup({cache: false});
});
getStatus();
});
function getStatus() {
$('div#content').load('ajax_stream.php').fadeIn("slow");
setTimeout("getStatus()",30000); // refresh every 30000 milliseconds (30 seconds)
}
</script>
It occurs to me that there needs to be some form of limitation so that after 'n' minutes, we stop refreshing the div - ie if a user leaves their browser open forever, we don't just keep consuming server resources.
How can I achieve this? Additionally, if I wanted to call a new file inside the DIV upon timeout, what is the best method?
Upvotes: 2
Views: 2553
Reputation: 12043
Here is how to do it:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
//when the page loads, the user is idle for 0 seconds
var idle=0;
$(function(){
$(document).ready(function(){
$.ajaxSetup({cache: false});
});
getStatus();
});
function getStatus() {
idle+=1;
//if idle for 5 minutes, do nothing
if (idle==10) return;
$('div#content').load('ajax_stream.php').fadeIn("slow");
setTimeout("getStatus()",30000); // refresh every 30000 milliseconds (30 seconds)
}
//reset the counter whenever an activity is done on the page
$('body').mousemove(function(){
idle=0;
});
</script>
Upvotes: 0
Reputation: 12043
I think the best solution for you is to set a global variable, that increments each time getStatus() is executed, and set it back to 0 on $('body').mousemove(); (this is the behaviour that Gmail uses to set user status to IDLE on web gmail chat)
Upvotes: 0
Reputation: 59343
How about this solution?
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
var statusUpdateTimeout = null;
$(function(){
$(document).ready(function(){
$.ajaxSetup({cache: false});
});
// Run get status and repeat every 30 seconds
getStatus();
statusUpdateTimeout = setInterval("getStatus()", 30000);
// Stop updating after 15 minutes
setTimeout(function() {
if(statusUpdateTimeout) clearInterval(statusUpdateTimeout);
}, 900000);
});
function getStatus() {
$('div#content').load('ajax_stream.php').fadeIn("slow");
}
</script>
I replaced the setTimeout
with a setInterval
and moved it outside the getStatus
function. Also I set a new timeout that will stop the interval after 15 minutes.
Also for future reference, please indent your code properly so that it's readable to others.
Upvotes: 3
Reputation: 2128
maybe you could, just store the timeout and check if the time in milliseconds is lower then the time in minutes you want the script to stop ?
var timerunning;
...
timerunning = timerunning + 30000;
if(timerunning < 120000){
setTimeout("getStatus()",30000);
}
didn't test though, good luck :)
Upvotes: 5