Timers and browsers - unfocused or minimized window - javascript

I have a javascript Timer that perform an AJAX request, I need to know if there is any browser/os combination that stops executing timers when the user minimizes or unfocus the browser window.
Anyone seen a comprehensible test case about this around the web?

Perhaps you could use what Patrick said window.onblur and clearInterval. Example of clearInterval: http://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval3

Related

WebDriver.io: how to make browser pause/ wait?

For testing, I am loading a page and clicking a button, I am using webdriver.io for testing Since the page is quite heavy, it takes a bit of time to load, I would like the global variable browser to wait few seconds before clicking the button.
I know there is waitForVisible method, but not good enough, I still have no idea if the js has added click event to the button, I am looking for something similar to sleep method in selenium webdriver.
I think you are asking about the pause() method:
pauses queue execution for a specific amount of time
Since using pause() is not a good practice, you can use waitForExist() as an alternative

Emulate Javascript 'alert' blocking nature

Is it possible to create a custom modal message which 'blocks' the execution of the script until a user input?
For example, how can you achieve this without using the native window alert / prompt functions?
setInterval(function(){
alert('Click OK to Continue'); // timing stops until user hits ok
},4000);
I know you could have your custom dialog invoke a callback function on user input, but I'm interested in being able to force this blocking behaviour
Is it possible to create a custom modal message which 'blocks' the execution of the script until a user input?
No. There is no way to block either execution or user interaction as effectively as a native popup (since with custom popups the user is always technically capable of using developer tools to get out of it).
However, as pst says in the comments on the question, asynchronous lightboxes are not onerous, and are almost as effective at blocking user interaction as popups, so I recommend finding a library that provides lightboxes you like and running with that.
For example, how can you achieve this without using the native window alert / prompt functions?
You can't use that code to do what you say it will even with native window alert / prompt functions (see this fiddle - wait 4 seconds before closing popup). You'd need the following:
function timeoutFunction() {
alert('Click OK to Continue'); // timing ACTUALLY stops until user hits ok
setTimeout(timeoutFunction, 4000);
}
setTimeout(timeoutFunction,4000);
Which is something that you can't implement (precisely - see above on lightboxes) without native popups.
Even while(true) loops won't generally block as well as a popup - firefox at least has a "stop script" message that pops up after it's been going too long, and I'm fairly sure other major browsers do too.
No, you can't (at least not in a browser). Javascript APIs are mostly async. alert/prompt are exceptions. However, it's not very hard to work with async prompts and callbacks.
A bit old, but in case it helps, I've found my solution with this:
var answer = confirm("are you sure?");
if(!answer)return;

JavaScript code stops when losing focus

Our project uses a variety of libraries (Kinetic Js, jquery, buzz.js, etc..), we have a lot of animations going on and some sounds playing simultaneously ,our purpose is stop all the JavaScript processes when a user change the tab or the window of the browser, losing focus.
We know that the onBlur and onFocus gives us the ability to detect that change and with one setTimeOut function we can stop it. We want to know if there is a more efective way of doing that or a more low level solution.
Thanks in advance.
These days, there's requestAnimationFrame() http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/RequestAnimationFrame/Overview.html
Article with info about browser support, and how to emulate in browsers that do not support it: http://paulirish.com/2011/requestanimationframe-for-smart-animating/.

How do you stop an infinite loop in Javascript?

Let's say I accidentally wrote this:
do { } while (true);
...and then ran it. Apart from killing your browser, is there a way to stop javascript execution (the equivalent of Ctrl+Break in basic, or Ctrl+C)?
Normally, after about 30 seconds your browser asks if you want to stop the long-running script, but this doesn't always happen (as I just found out)!
FYI: A simple loop such as this: for (i=1; i > 0; ++i); will cause my browser to crash (Firefox 3.5b4). I don't feel much like testing to see if it's any of my add-ons. Continuously restarting my browser isn't my idea of a fun Monday night.
2018 update:
In Chrome 67, if you have the DevTools open (F12), you can end the infinite loop without killing the whole tab:
Go to the Sources panel and click "Pause script execution".
Hold that same button and now select the "Stop" icon.
https://developers.google.com/web/updates/2018/04/devtools#stop
I'm using Chome Version 45.0.2454.101
At the top right hand corner, at the hamburger menu, click on More Tools > Task Manager, and then kill the tab from there. This is if attempting to close the tab fails. Otherwise a simple 'X' on the tab kills it.
At least with Chrome, you may be able to kill off the individual tab and not the whole application.
Randolpho has also informed me that IE8 has similar functionality.
If you are using Chrome you can easily kill not responding tab:
Switch to any other tab
Press Shift + Esc to open Chrome's Task Manager
Find your tab in the list (Should be the most memory consumer)
Click End Process
Important: Navigating to another tab is important, because if you are on the original tab JavaScript will make the browser unable to process your key press and do nothing because of its infinite loop.
ref: https://superuser.com/questions/92617/stop-never-ending-popup-alerts-in-firefox
Firefox is particularly problematic ...
Warning! Caveat! Do NOT run this!
javascript:
while (true) alert("irritated and exhausted - yet?");
This will go "infinite" and will NOT exhaust an internal timeout since the script will not chew up CPU time fast enough. In FF 11 this guarantees there will be no "unresponsive script" abortion opportunities.
Gracefully stopping just the offending script was possible and trivial in early browser versions, using manual intervention, without croaking and aborting the whole browser. To not have such control is a major browser software design flaw. Unreasonable dexterity and reflex are required to effect the manual motor mechanics of the "solutions" described in the reference.
Caveat: It is possible for scripts to go "infinite" w/o timing out AND w/o alert type prompts. These are particularly pernicious and annoying. Basically, the scripts run slowly enough so that the CPU time cycle allotment of say 20 sec. is stretched out over several minutes or hours or ..., before timing out, by suspension of execution pending resumption on an event trigger. Instead of timing CPU cycles it would be far better for scripts to timeout on real world clocking. (Ever notice how you cannot abort a script that is trying to retrieve content - but unsuccessfully - for constructing a page? In FF both the address bar buttons reload and cancel/stop are disabled though the tab at least can be closed.) Normal javascript Timeout() and setInterval() calls do not suffer from this and are conditioned so that while suspended, manual intervention is possible to abort them "gracefully".
Test environment for empirical observations:
window.navigator.userAgent=
Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:11.0) Gecko/20100101 Firefox/11.0
PS. the script
for (i=1; i > 0; ++i);
will eventually trap on an overflow error when i exceeds the maximum value allowed.
Most browsers have a "slow script performance" warning that comes up when an out of control javascript is taking a very long time to execute. This warning dialog usually gives the option to kill the offending script.
Depends on the browser. Some let you click the "stop" button to stop javascript execution. Others don't.
I suggest the best way is to just kill the browser or tab entirely.
In Firefox
Go to Developer Tools > Debugger, and click pause button.
In Chrome
Go to Developer Tools > Sources, and click pause button.
most decent browsers do show an "unresponsive script" warning... If not, I guess your best course of action would be to find out why the warning is not popping up.
From https://superuser.com/questions/92617/stop-never-ending-popup-alerts-in-firefox#comment93927_92617, by anonymous:
This isn't a satisfactory general-purpose solution, but with Greasmonkey (or maybe Ubiquity or Jetpack) you could overwrite window.alert with a function that calls window.confirm and optionally throw(s) an error, stopping all script execution, or toggles a flag to stop alerts. That might be useful if a site you keep going back to presents this behavior.
What I do when using Chrome and this happens is hitting shift+ctrl+esc to bring up the windows taskmanager. Then switch to the processes-tab and scroll through the chrome.exe processes(chrome has one process for each open tab) till I find one with significantly higher cpu usage than the oters. It tends to have around 30% for me while all others have like 0-2%
Then I'll just end that process.
Actually the same can be done by going to tools>taskmanager or shift+esc in chrome to open its custom taskmanager for its processes. Might be easier to use that since it shows more info of the tabs.
Last resort: close the browser from the OS. I had good results closing Chrome from the taskbar in Windows 10 while an infinite loop ran. If that didn't work I would have killed the browser in Task Manager as above. On other OS's, of course the exact technique would vary.
Infinite recursions are less a problem. All systems I've seen limit the size of the execution stack, and interrupt with a runtime error eventually once infinite recursion leads to stack overflow (no pun intended).

Jquery Effect Onunload

I would like to use the jquery slideUp effect when the user navigates away from the page just to make the page look cool as it closes.
I assume that I should use the onunload event but how can I delay the page closing long enough for the effect to run to completion.
One of the options that came to mind is effectively hijacking the page closing function, storing it in some variable and then executing it once I had run my effect but I have no idea how I would do that.
Any suggestions or alternative ideas are more than welcome
what you're looking for is the onbeforeunload event.
just a warning though... it should be really quick... or your visitors are probably going to hate it no matter how cool it looks
as to preventing the page from navigating away before the animation is done, that's a bigger problem... any animation is going to rely on setTimeout/setInterval and the page won't wait for those to complete before leaving.
Doing anything but closing the window when the users ask to is breaking a contract with the user. The browser window is not yours, it's the users, and no matter how cool the effect, it will inevitably annoy most of your users.
The onbeforeunload event is very restricted in what it can do. It must return a string, which is then used to prompt the user for a confirmation about leaving the page. It won't work for cool animations.
As far as I know, the only way to stop a user from leaving a page is the onbeforeunload event, which isn't cancelable. Instead, you return a string from that method, the browser prompts the user with a Yes/No dialog, life goes on. 276660 has more info about this.
I don't think you're going to have much luck with this one.
why not, instead of making a "cool" effect when a user simple want to go away from your website (even if the user closes the browser/tab the unload event will be fired) and annoying the simple user with that ... preventing him/her to return again...
...do that "cool" effect when a user reaches your website for the first time? as a normal intro effect?
I did that as a simple idea, you can see it here: http://www.balexandre.com/jmfc
I would agree 100% with Jonathan Fingland's answer, and add this.
In IE, (I'm not sure what versions support this, I know IE6 did) you can use some propriety meta tags to achieve fades etc when leaving the page. However, this is limited in browsers (IE only), so you're stuck for cross browser use.
You may find loading new content via AJAX would give you better control of effects and transitions, as well as reducing the annoyance factor to the user which can result from trying to hijack the browser actions in such a manner.
I would look at using a form of slider as mentioned above (see for instance http://webdesignledger.com/tutorials/13-super-useful-jquery-content-slider-scripts-and-tutorials),
or simply loading content panes in response to user clicks.
The only way I've found for delaying the window to close, is using an alert. If this is an acceptable compromise for your case, it will really delay the window destruction in memory, and allow your page timers to execute (of course, if user does not close the alert popup earlier than your animations finalize).
I recently used this approach so i could call a flex method through FABridge (which would otherwise be destroyed before the flex method call finishes). I'd like to hear your comments on this.

Categories

Resources