Is there a way to pause a long polling script when someone leaves a page up but is not viewing it? So if I have multiple tabs or windows of the app open only the one I am activel开发者_JS百科y viewing would have the active long polling script running?
Actually there is no efficient way to pause script in javascript. But let me suggest one:
function pausecomp(millis){
var date = new Date();
var curDate = null;
do{
curDate = new Date();
}while(curDate-date < millis);
}
So this would pause the whole script for a number of milliseconds. However this isn't a good practice.
Javascript allows to setup events to occur after a delay:
setTimeout("alert('hello')",1250);
So when this line of code is reached the setTimeout method calls the alert when 1250 milliseconds are passed.
I hope this information helps you ;)
To detect when mouse leaves the window I have setup a jsfiddle for you: http://jsfiddle.net/xPAwu/1/
Besides there are actually some questions on that on stackoverflow: How can I detect when the mouse leaves the window?
Javascript event when mouse leaves browser window
The difficulty here is knowing if the user is actually idle or not. I have used this idleTimer plugin in the past and it seemed to work out pretty well. The author uses a combination of events (mousemove keypress, etc) to decide if the user is active or not.
You could see how much time the page is idle:
<script>
$(document).ready(function(){
var lastEventTime = null;
//Detect a user interaction
$(document).bind("mousemove keyup mousewheel", function(event){
lastEventTime = new Date(); //Store last event time
});
setInterval(function(){
var currentTime = new Date();
var idleSeconds = (currentTime.getTime() - lastEventTime.getTime())/1000;
if( idleSeconds > 60) return; //If more than 60 seconds idle, stop polling
pollingScript(); //Here goes your script
}, 1000);
});
</script>
What we're doing, is capture when there's a user interaction (move mouse or press a key). If it didn't happen for a long time (60 seconds in this example), we stop executing our polling script.
Hope this helps
精彩评论