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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There is no direct way unless you use browser-specific code, or code that’s not completely standard (see katspaugh’s answer).
‘Stop’ solution
design your code so that it is “stoppable”. That’s something you have to figure out for your context.
Then add something like below:
..
‘Assert’ solution
Insert the following code where it really matters that the window has focus:
There are different methods for testing if window has focus: JavaScript / jQuery: Test if window has focus
Asyncronous solution
One of two possible implementations exist…..
Waiting via setTimeout
Waiting via custom events
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.onfocusfunction (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, thewindow.onfocusfunction will simply trigger some custom event, and you don’t have to manually writing any looping code with setTimeout.