Is it possible in javascript to only execute javascript if the user is on the actual tab/page?
Like if he switches to another tab then the javascript process will be paused and when he returns to the tab the javascript will continue the process.
Is it possible in javascript to only execute javascript if the user is on the actual tab/page?
Like if he switches to another tab then the javascript process will be paused and when he returns to the tab the javascript will continue the process.
There is no direct way unless you use browser-specific code, or code that's not completely standard (see katspaugh's answer).
design your code so that it is "stoppable". That's something you have to figure out for your context.
Then add something like below:
..
<html>
<head>
</head>
<body>
<script>
window.onblur = function() {
yourStopFunctionHere().
}
</script>
</body>
</html>
Insert the following code where it really matters that the window has focus:
if(windowHasFocus()) {
//your code here
}
There are different methods for testing if window has focus: JavaScript / jQuery: Test if window has focus
whenWindowHasFocus(fn); //where fn is the function you want to only run when window has focus
One of two possible implementations exist.....
function WhenWindowHasFocus(yourFunction){
if(windowHasFocus()) {
yourFunction();
}
setTimeout(function(){ WhenWindowHasFocus(yourFunction); }, 1000);
}
Or even better, if you can wrap the window-focused-dependent functionality (the functionality dependent on the window having focus) into a separate function, then "hook" that function to window.onfocus. Be careful with this one though. You don't wan't to completely overwrite the window.onfocus
function (or you undo the previous work you just did). Instead, you may have to use custom events of some sort. Most js frameworks provide custom events. If you go this route, the window.onfocus
function will simply trigger some custom event, and you don't have to manually writing any looping code with setTimeout.
//The below is pseudo-code. custom events differ between js frameworks
window.onfocus = function(){
window.FocusEvent.trigger()
}
function WhenWindowHasFocus(yourFunction){
if(windowHasFocus()) {
yourFunction();
}
window.focusEvent.addOnlyOnce(yourFunction);
}