How does a browser determine that a script has run for too long ? Is it actually configurable through some advanced settings ?
3
This is probably not the answer you expected but it might be useful to somebody else. I only know the details for Firefox but I assume that the other browsers do something similar (at least the ones that limit script execution, see the link provided by Yannis Rizos in the comments).
JavaScript in the browser is generally single threaded and event driven. This means that there is an event queue somewhere and the browser is processing the queued events in a loop. The events posted to the event queue can be both “real” events (e.g. keyboard input) or synthesized events (created by JavaScript code, native code or things like timeouts). The processing of these events might involve JavaScript code (e.g. event handlers in a web page) but it doesn’t have to – an event could be handled in native code only. It is essential that processing of an event is fast because it delays processing of all other events, including the ones essential to keep the browser UI working – the user perceives lack of event processing as a hang.
So the trick Firefox is using: there is a thread checking regularly how long the processing of the current event takes (how much time has been spent outside the event processing loop so far). If it exceeds a certain threshold (determined by the dom.max_script_run_time
preference for web scripts and dom.max_chrome_script_run_time
for browser’s own scripts) this thread checks the stack of the main thread – and if it finds a JavaScript frame on the stack it suspends it. The “unresponsive script” warning shows up and the browser returns to processing the event queue temporarily. If you decide to stop the script then this JavaScript code is stopped. I’m not certain how exactly it is being stopped but probably by generating a JavaScript exception which cannot be caught – something that doesn’t always work correctly if native and JavaScript stack frames are interleaved.
The real implementation is of course more complicated than what I explained above (e.g. when it comes to modal dialogs) but this should be enough to get you started if you want to find out more.